1.pom.xml文件搭建mybatis3环境
<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.xuebaosoft.mybatis3</groupId> <artifactId>mybatis-annotation</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>mybatis-annotation</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> </dependencies> </project>
2.这里是用MyEclipse10建的一个Java-Maven工程,结构如下,
3.先看一下配置文件mybatis-config.xml(仅仅配置了datasource)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-config.dtd"> <configuration> <environments default="environment"> <environment id="environment"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://192.168.191.1:3306/xuebaodb?characterEncoding=UTF-8" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <!-- <mappers> <mapper resource="User.xml" /> </mappers> --> </configuration>
4.为了节省篇幅,仅给出*ServiceImpl源码,源码中仅涉及基本的增删改查操作
package com.xuebaosoft.mybatis3.mybatis_annotation.service.impl; import java.util.ArrayList; import java.util.List; import org.apache.ibatis.session.SqlSession; import com.xuebaosoft.mybatis3.mybatis_annotation.dao.UserDao; import com.xuebaosoft.mybatis3.mybatis_annotation.model.User; import com.xuebaosoft.mybatis3.mybatis_annotation.service.UserService; import com.xuebaosoft.mybatis3.mybatis_annotation.util.SqlSessionFactoryUtil; public class UserServiceImpl implements UserService { public void add(String id, String username, String password) { SqlSession session = SqlSessionFactoryUtil.getInstance().openSession(); try { session.getMapper(UserDao.class).add(id, username, password); session.commit();// 提交事务 } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } } public void delete(String id) { SqlSession session = SqlSessionFactoryUtil.getInstance().openSession(); try { session.getMapper(UserDao.class).delete(id); session.commit();// 提交事务 } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } } public int update(String username, String password, String id) { int count = 0; SqlSession session = SqlSessionFactoryUtil.getInstance().openSession(); try { count = session.getMapper(UserDao.class).update(username, password, id); session.commit();// 提交事务 } catch (Exception e) { count = 0; e.printStackTrace(); } finally { session.close(); } return count; } public List<User> getUsers(int offset, int pageSize) { List<User> users = new ArrayList<User>(); SqlSession session = SqlSessionFactoryUtil.getInstance().openSession(); try { users = session.getMapper(UserDao.class).getUsersByPage(offset, pageSize); } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } return users; } }
5.给出本人封装的一个util工具用于获取SqlSessionFactory,即SqlSessionFactoryUtil.java,
package com.xuebaosoft.mybatis3.mybatis_annotation.util; import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.xuebaosoft.mybatis3.mybatis_annotation.dao.UserDao; public class SqlSessionFactoryUtil { private static SqlSessionFactory sqlSessionFactory = null; public static SqlSessionFactory getInstance() { if (sqlSessionFactory == null) { String resource = "mybatis-config.xml"; InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); } catch (IOException e) { e.printStackTrace(); } sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 注解方式查询时需要注册MAPPER sqlSessionFactory.getConfiguration().addMapper(UserDao.class); } return sqlSessionFactory; } }
6.给出model--User.java,
package com.xuebaosoft.mybatis3.mybatis_annotation.model; public class User { private String id; private String username; private String password; //省略getter和setter。。。 }
7.给出注解的最终实现形式--UserDao.java,这也就是所谓的mybatis的注解使用方式,注解的语法比较通俗易懂,但是还是得自己花时间去熟悉才能运用自如,本篇不作介绍
package com.xuebaosoft.mybatis3.mybatis_annotation.dao; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import com.xuebaosoft.mybatis3.mybatis_annotation.model.User; public interface UserDao { @Insert(" insert into users (id,username,password) values (#{id},#{username},#{password})") public void add(@Param("id") String id, @Param("username") String username, @Param("password") String password); @Delete(" delete from users where id=#{id}") public void delete(String id); @Update(" update users set username=#{username},password=#{password} where id=#{id}") public int update(@Param("username") String username, @Param("password") String password, @Param("id") String id); @Select(" select * from users where id=#{id}") public User getUser(String id); @Select(" select * from users order by id asc ") public List<User> getUsers(); @Select(" select * from users order by id asc limit #{pageSize} offset #{offset} ") public List<User> getUsersByPage(@Param("offset") int offset, @Param("pageSize") int pageSize);// offset=pageSize*(page-1) }
解释下@Param ,例如
@Param("username") String username
是让String username对应sql中#{username},如果Java代码里的参数名字跟sql里的参数名字一致则不需要写@Param注解
8.用junit测试一下,
package com.xuebaosoft.mybatis3.mybatis_annotation; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import com.xuebaosoft.mybatis3.mybatis_annotation.model.User; import com.xuebaosoft.mybatis3.mybatis_annotation.service.UserService; import com.xuebaosoft.mybatis3.mybatis_annotation.service.impl.UserServiceImpl; public class AppTest extends TestCase { public AppTest(String testName) { super(testName); } public static Test suite() { return new TestSuite(AppTest.class); } public void testApp() { UserService userService = new UserServiceImpl(); userService.add("1002", "张三", "112"); List<User> list = userService.getUsers(0, 1);//分页查询 System.out.println(list); } }
9.备注,如果增加一个业务,如图,
即增加了T_UserMapper.java这个业务,那么需要增加的配置如下,