公司最近起了一个新项目,之前一直使用的是Strut + Spring + hibernate;由于新项目比较小,使用ssh有点杀鸡用牛刀的意思,经过评估后,感觉mybatis比Hibernate要简单的很多。
通过注解的方式开发,可以减少spring和mybatis的很多xml配置,当然spring还是得有部分的xml配置,除非使用spring官网提倡的REST风格;对于REST风格 俺不太熟悉,这里就不献丑啦。
咱们使用Maven进行项目开发,在jar管理方面要省心很多。
第一步 加载所需要的jar包,pom.xml的配置如下:
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring-framework.version>3.2.5.RELEASE</spring-framework.version> <mysql.driver.version>5.1.27</mysql.driver.version> <c3p0.version>0.9.1.2</c3p0.version> <javassist.version>3.17.1-GA</javassist.version> <log.slf4j.version>1.7.5</log.slf4j.version> <log4j.version>1.2.17</log4j.version> <commons.lang.version>2.6</commons.lang.version> <servlet.version>2.5</servlet.version> <jstl.version>1.2</jstl.version> <jsp.version>2.2</jsp.version> <tomcat.plugin.version>2.2</tomcat.plugin.version> <junit.version>4.11</junit.version> <javax.mail.version>1.5.1</javax.mail.version> <mybatis-spring.version>1.2.2</mybatis-spring.version> <mybatis.version>3.2.7</mybatis.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring-framework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring-framework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring-framework.version}</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>${c3p0.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.driver.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${log.slf4j.version}</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>${commons.lang.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> </dependency> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>${javax.mail.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring-framework.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> </dependencies>
这里主要是加载mybatis-spring和mybatis。
第二步 设置mybatis需要的sqlSessionFactory,并且让mybatis自动加载Mapper接口(该接口在下面会说)
<context:property-placeholder location="classpath:spring/jdbc.properties" /> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <!-- 解决初次链接 链接已被释放 start --> <property name="acquireRetryAttempts" value="30" /> <property name="acquireRetryDelay" value="1000" /> <property name="testConnectionOnCheckin" value="true" /> <property name="automaticTestTable" value="C3P0TestTable" /> <property name="idleConnectionTestPeriod" value="14400" /> <property name="checkoutTimeout" value="3000" /> <!-- 解决初次链接 链接已被释放 end --> <property name="driverClass" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="initialPoolSize" value="${jdbc.initialPoolSize}" /> <property name="minPoolSize" value="${jdbc.minPoolSize}" /> <property name="maxPoolSize" value="${jdbc.maxPoolSize}" /> </bean> <!-- sql session factory to create sql session --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.wangjin.admin.mapper" /> </bean> <!-- configuration for transaction --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean>
第三步 书写Mapper 接口,该接口相当于普通项目的Dao类,但是该Mapper是接口的形式并且通过注解的方式进行sql声明,mybatis会通过代理的方式执行相应的sql,在第二步中已经设置了让mybatis来加载Mapper接口。
public interface AdminUserMapper { @Insert("insert into admin_user(username, password) values(#{username}, #{password})") @SelectKey(statement="SELECT last_insert_id() as id", keyProperty="id", before=false, resultType=int.class) public int add(AdminUser adminUser); @Delete("delete from admin_user where id=#{id}") public void delete(@Param("id")int id); @Update("update admin_user set username=#{username}, password=#{password} where id=#{id}") public void update(AdminUser adminUser); @Select("select * from admin_user") public List<AdminUser> loadAll(); @Select("select * from admin_user limit #{start}, #{size}") public List<AdminUser> loadAllLimit(@Param("start")int start, @Param("size")int size); @Select("select * from admin_user where id=#{id}") public AdminUser getById(@Param("id")int id); @Select("select * from admin_user where username=#{username}") public AdminUser getByUsername(@Param("username")String username); }
这里要注意在Mapper中一定不要有相同名称的方法,要不然会出错。
@SelectKey(statement="SELECT last_insert_id() as id", keyProperty="id", before=false, resultType=int.class)
这句注解表示插入成功后,将主键设置到adminUser中, 当然AdminUser一定要有id的set方法, AdminUser的详情如下
public class AdminUser { private int id; private String username; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
第四步 在service中使用Mapper接口(相当于在service中使用Dao),你会发现以前需要进行Dao的接口设计以及Dao接口的实现,很麻烦,现在这些都不需要啦,只需要定义Mapper接口,然后定义相关的接口方法,在相关的方法上声明sql语句,然后在service中就可以使用该接口啦。
public interface AdminUserService { public int addAdminUser(AdminUser adminUser); public void deleteAdminUserById(int id); public void updateAdminUser(AdminUser adminUser); public AdminUser getByUsername(String username); public List<AdminUser> loadAllAdminUsers(); public List<AdminUser> loadAllAdminUsers(int start, int size); } /** * service for admin user * @author kinfer * */ @Service public class AdminUserServiceImpl implements AdminUserService { @Autowired private AdminUserMapper adminUserMapper; @Override @Transactional public int addAdminUser(AdminUser adminUser) { return adminUserMapper.add(adminUser); } @Override @Transactional public void deleteAdminUserById(int id) { adminUserMapper.delete(id); } @Override @Transactional public void updateAdminUser(AdminUser adminUser) { adminUserMapper.update(adminUser); } @Override @Transactional(readOnly=true) public AdminUser getByUsername(String username) { return adminUserMapper.getByUsername(username); } @Override @Transactional(readOnly=true) public List<AdminUser> loadAllAdminUsers() { return adminUserMapper.loadAll(); } @Override @Transactional(readOnly=true) public List<AdminUser> loadAllAdminUsers(int start, int size) { return adminUserMapper.loadAllLimit(start, size); } }
第五步 测试,我使用的是springjunit
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:spring/business-config.xml") public class AdminUserServiceTester { @Autowired private AdminUserService service; @Test public void addTest(){ AdminUser adminUser = service.getByUsername("kinfer"); if(adminUser != null){ service.deleteAdminUserById(adminUser.getId()); } else{ adminUser = new AdminUser(); adminUser.setUsername("kinfer"); adminUser.setPassword("0000"); } int result = service.addAdminUser(adminUser); Assert.assertTrue(result > 0); Assert.assertTrue(adminUser.getId() > 0); adminUser = service.getByUsername("kinfer"); Assert.assertTrue(adminUser != null); Assert.assertEquals("kinfer", adminUser.getUsername()); adminUser.setUsername("kinfer1"); service.updateAdminUser(adminUser); adminUser = service.getByUsername("kinfer1"); Assert.assertTrue(adminUser != null); Assert.assertEquals("kinfer1", adminUser.getUsername()); adminUser.setUsername("kinfer"); service.updateAdminUser(adminUser); } }
完成spring+mybatis配置,是不是很easy.