引言
本文主要从一个基础实例,讲解Mybatis的实现,已经每一步的详细讲解。我会将项目共享在百度云盘,文章最后!
1、项目结构
2、项目配置
2.1 配置SqlMapConfig.xml
根据Mybatis架构图, 我们第一步应该配置SqlMapConfig,主要涉及到数据源的一些配置。架构请参考教材1
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--与spring整个后环境配置将废除--> <environments default="development"> <environment id="development"> <!--使用JDBC事务管理--> <transactionManager type="JDBC"></transactionManager> <!--数据库连接池--> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/shiro?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertTonull"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <!--加载mapper--> <mappers> <mapper resource="mapper/UserMapper.xml"/> </mappers> </configuration>
2.1 配置sqlsessionFactory.xml
在配置SqlMapConfig中我们看到userMapper.xml,下面详细讲解如果配置sqlsessionFactory、sqlsession、mapperStatement、Executor
2.1.1Orm数据实体映射配置
我们每一个对象映射到关系型数据的一些操作,mybatis也是一种orm模型,自然免不了映射,我们以Mysql的User数据表为例子
数据库:user表
Java对象:User
public class User { private int id; private String username;// 用户姓名 private String sex;// 性别 private Date birthday;// 生日 private String address;// 地址 //自己添加get set方法 }2.1.1mapperStatement配置
我们的以一个User为例,创建 UserMapper.xml配置文件。把一个sql称为一个statement,这里很多mapperStatement,所以这映射文件里面,把对User的操作的sql都放在里面,即构建了mapperStatement。
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--命名空间:分类管理sql隔离,方便管理--> <mapper namespace="test"> <!--id标示一个sql语句,一个Statement,封装为一个MapperStatement--> <!--parameterType:传入参数类型;resultType:输出结果类型,指定映射的pojo--> <!--#{}标示一个占位符,--> <!--查询用户--> <select id="getUserById" parameterType="int" resultType="com.ycy.mybatis.module.User"> SELECT * FROM USER WHERE id=#{id} </select> <select id="findUserByName" parameterType="java.lang.String" resultType="com.ycy.mybatis.module.User"> SELECT * FROM USER WHERE username LIKE '%'||#{username}||'%' </select> <!--新增用户--> <insert id="insertUser" parameterType="com.ycy.mybatis.module.User" > <!--插入值之后返回主键值--> <selectKey resultType="int" order="AFTER" keyProperty="id"> SELECT LAST_INSERT_ID() </selectKey> INSERT INTO USER (username,birthday,sex,address) VALUES (#{username},#{birthday},#{sex},#{address}) </insert> <!--删除用户--> <delete id="deleteUser" parameterType="int"> DELETE FROM USER WHERE id=#{id} </delete> <!--更新用户--> <update id="updateUser" parameterType="com.ycy.mybatis.module.User"> UPDATE USER SET username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} WHERE id=#{id} </update> </mapper>2.1.1sqlsessionFactory创建sqlsession
我们必须知道,所有的sql配置都是需要一个sqlsession来执行会话操作,因为session本身意思就是一次会话。需要sqlsession就必须构建一个sqlsessionFactory,下面我们用两种方式来建立会话,进行数据库操作。
2.1.1.1通过junit测试操作会话
我们直接在junit中读取sqlMapConfig.xml,调用会话
测试类:MybatisFrist
import com.ycy.mybatis.module.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; /** * Created by Administrator on 2015/8/28 0028. */ public class MybatisFrist { private SqlSessionFactory sqlSessionFactory = null; //创建工厂 @Before public void before() throws IOException { //创建会话工厂 String resource = "SqlMapConfig.xml"; InputStream in = null; in = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); } @Test public void testGet() { //1通过sqlsessionfactory创建sqlsession SqlSession sqlSession = sqlSessionFactory.openSession(); //2通过sqlsession操作数据库 User user = sqlSession.selectOne("test.getUserById", 1); System.out.println(user.getUsername()); sqlSession.close(); } @Test public void testSelect() { //1通过sqlsessionfactory创建sqlsession SqlSession sqlSession = sqlSessionFactory.openSession(); //2通过sqlsession操作数据库 List<User> userList = sqlSession.selectList("test.findUserByName", "小"); System.out.println(userList.size()); for (User user : userList) { System.out.println(user.getUsername()); } sqlSession.close(); } @Test public void testInsert() { User user = new User(); user.setUsername("杨长用"); user.setAddress("重庆"); user.setBirthday(new Date()); user.setSex("1"); //1通过sqlsessionfactory创建sqlsession SqlSession sqlSession = sqlSessionFactory.openSession(); //2通过sqlsession操作数据库 sqlSession.insert("test.insertUser", user); sqlSession.commit(); sqlSession.close(); System.out.println("--------" + user.getId()); } @Test public void testDel() { //1通过sqlsessionfactory创建sqlsession SqlSession sqlSession = sqlSessionFactory.openSession(); //2通过sqlsession操作数据库 sqlSession.insert("test.deleteUser", 27); sqlSession.commit(); sqlSession.close(); } @Test public void testUpdate() { User user = new User(); user.setUsername("杨长用修改"); user.setAddress("重庆"); user.setBirthday(new Date()); user.setSex("1"); user.setId(27); //1通过sqlsessionfactory创建sqlsession SqlSession sqlSession = sqlSessionFactory.openSession(); //2通过sqlsession操作数据库 sqlSession.insert("test.updateUser", user); sqlSession.commit(); sqlSession.close(); System.out.println("--------" + user.getId()); } }2.1.1.2通过接口的方式操作会话
请注意以上直接读取文件的方式,与通过接口方式的区别。我们只是把操作封装了一下,因为实际项目我们不可能写硬编码(直接写死参数值),仍然用junit测试。
Java对象:UserService
public interface UserService { public User getUserById(int id) throws Exception; public List<User> findUserByName(String name) throws Exception; public void insertUser(User user) throws Exception; }Java对象:UserService
package com.ycy.mybatis.dao.impl; import com.ycy.mybatis.dao.UserService; import com.ycy.mybatis.module.User; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import java.util.List; /** * Created by Administrator on 2015/8/31 0031. */ public class UserServiceImpl implements UserService { private SqlSessionFactory sqlSessionFactory; public UserServiceImpl(SqlSessionFactory sqlSessionFactory){ this.sqlSessionFactory=sqlSessionFactory; } @Override public User getUserById(int id) throws Exception { SqlSession sqlSession=sqlSessionFactory.openSession(); User user= sqlSession.selectOne("test.getUserById", id); sqlSession.close(); return user; } @Override public List<User> findUserByName(String name) throws Exception { SqlSession sqlSession=sqlSessionFactory.openSession(); List<User> userList= sqlSession.selectList("test.findUserByName", name); sqlSession.close(); return userList; } @Override public void insertUser(User user) throws Exception { SqlSession sqlSession=sqlSessionFactory.openSession(); //2通过sqlsession操作数据库 sqlSession.insert("test.insertUser", user); sqlSession.commit(); sqlSession.close(); } }
测试类:MybatisTest2由于篇幅关系,我们只做根据Id查询用户
package com.ycy.mybatis.test; import com.ycy.mybatis.dao.impl.UserServiceImpl; import com.ycy.mybatis.module.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; /** * Created by Administrator on 2015/8/31 0031. */ public class MybatisTest2 { private SqlSessionFactory sqlSessionFactory = null; @Before public void before() throws IOException { String resource="SqlMapConfig.xml"; InputStream in =Resources.getResourceAsStream(resource); sqlSessionFactory= new SqlSessionFactoryBuilder().build(in); } @Test public void testGet() throws Exception { UserServiceImpl userService=new UserServiceImpl(sqlSessionFactory); User user= userService.getUserById(1); System.out.println(user.getUsername()); } }输出结果:
本项目1-5章 初级教程 项目百度分享盘: