这是一个简单的案例,旨在说明spring如何与mybatis整合。以下是整个整合过程的说明。
一、整合前准备
数据库:oracle11g
开发工具:netbeans8.1
以下是我整个项目的文件结构图
二、创建项目
1.数据库建表
create table t_user( id number, name varchar2(100), age number )
2.在netbeans中创建Maven项目
项目清单:
(1)pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zj</groupId> <artifactId>springAndMybatis</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>springAndMybatis</name> <properties> <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.2.2.RELEASE</version> <type>jar</type> </dependency> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>4.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>ojdbc</groupId> <artifactId>ojdbc</artifactId> <version>14</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> </dependencies> <build> </build> </project>
注意:oracle的jar包需要将本地的ojdbc.jar导入本地maven库中。
(2)创建实体类User
package com.zj.model; /** * * @author ziJun */ public class User { private Long id; private String name; private Integer age; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "id=" + id + ", name=" + name + ", age=" + age + ‘}‘; } }
(3)创建UserMapper接口
package com.zj.mapper; import com.zj.model.User; /** * * @author ziJun */ public interface UserMapper { void insertUser(User user); User selectUserById(Integer id); }
(4)创建UserMapper接口映射文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC ‘PUBLIC:-//mybatis.org//DTD Mapper 3.0//EN‘ ‘http://mybatis.org/dtd/mybatis-3-mapper.dtd‘> <mapper namespace="com.zj.mapper.UserMapper"> <insert id="insertUser" parameterType="User"> <![CDATA[ insert into t_user(id,name,age) values(#{id},#{name},#{age}) ]]> </insert> <select id="selectUserById" parameterType="Integer" resultType="User"> <![CDATA[ select id,name,age from t_user where id=#{id} ]]> </select> </mapper>
该文件放在config/mapping文件夹下。
(5)创建业务层UserService接口及实现类
package com.zj.service; import com.zj.model.User; /** * * @author ziJun */ public interface UserService { void addUser(User user); User getUserById(Integer id); }
package com.zj.service.impl; import com.zj.mapper.UserMapper; import com.zj.model.User; import com.zj.service.UserService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; /** * * @author ziJun */ @Service("userService") public class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; @Transactional public void addUser(User user) { userMapper.insertUser(user); } public User getUserById(Integer id) { return userMapper.selectUserById(id); } }
(6)创建log4j配置文件
log4j.rootLogger=INFO, stdout,logfile # standard out log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n # Log File log4j.appender.logfile=org.apache.log4j.RollingFileAppender log4j.appender.logfile.File=${catalina.home}/logs/testMyBatis.log log4j.appender.logfile.MaxFileSize=20MB log4j.appender.logfile.MaxBackupIndex=1 log4j.appender.logfile.Encoding=GBK log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
该文件放在config根目录下。
(7)创建数据源配置文件jdbc.properties
db.driver=oracle.jdbc.driver.OracleDriver db.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl db.username=mybatis db.password=mybatis
该文件放在config/properties文件夹下。
(8)创建spring配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd "> <!--启用spring注解--> <context:annotation-config/> <!--DB配置文件--> <context:property-placeholder location="classpath*:config/properties/jdbc.properties"/> <!--自动扫描--> <context:component-scan base-package="com.zj"/> <!--配置数据源--> <bean id="baseDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${db.driver}" /> <property name="jdbcUrl" value="${db.url}" /> <property name="user" value="${db.username}" /> <property name="password" value="${db.password}" /> </bean> <!--配置mybatis--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--指定数据源 --> <property name="dataSource" ref="baseDataSource"/> <!--指定实体类所在包--> <property name="typeAliasesPackage" value="com.zj.model"/> <!--指定mybatis的映射文件--> <property name="mapperLocations" value="classpath:config/mapping/*.xml"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.zj.mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!--配置spring事务管理(注解)--> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="baseDataSource"/> </bean> <tx:annotation-driven transaction-manager="txManager"/> </beans>
三、测试项目
创建Junit单元测试
import com.zj.model.User; import com.zj.service.UserService; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * * @author ziJun */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:config/spring/spring.xml"}) public class TestMybatis { @Resource private UserService userService; private Logger log = Logger.getLogger(TestMybatis.class); @Test public void TestMybatis() { /*添加User*/ User user1 = new User(); user1.setId(Long.valueOf("2")); user1.setName("tom"); user1.setAge(30); userService.addUser(user1); /*查询添加的User*/ User user = userService.getUserById(2); log.info(user.toString()); } }
时间: 2024-10-01 19:03:48