一 SqlSession使用范围
- SqlSessionFactoryBuilder
- 通过SqlSessionFactoryBuilder创建会话工厂SqlSessionFactory
- 将SqlSessionFactoryBuilder当作一个工具类使用即可,不需要使用单例管理SqlSessionFactoryBuilder。
- 在需要创建SqlSessionFactory时候,只需要new一次SqlSessionFactoryBuilder 即可
- SqlSessionFactory
- 通过SqlSessionFactory创建SqlSession使用单例模式管理SqlSessionFactory(工厂一旦创建,使用一个实例)
- 将来mybatis和spring整合后使用单例模式管理sqlSessionFactory
- SqlSession
- SqlSession是一个面向用户(程序员)的接口
- SqlSession中提供了很多操作数据库的方法,例如:selectOne/selectList
- sqlSession是线程不安全的,在SqlSession实现类中除了有接口中的方法(操作数据库的方法)还有ukulel域属性
- SqlSession最佳应用场合在方法体内,定义成局部变量使用
二 mybatis开发dao方法-原始dao开发方法-程序员需要写dao接口和dao实现类
1 UserDao.java
package dao;
import entity.User;
public interface UserDao {
//根据id查询信息
public User findUserById(int id) throws Exception;
//添加用户信息
public void insertUser(User user) throws Exception;
//删除用户信息
public void deleteUser(int id) throws Exception;
}
2 UserDaoImpl.java
package dao.impl;
import dao.UserDao;
import entity.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.Date;
public class UserDaoImpl implements UserDao {
//需要向dao实现类中注入SqlSessionFactory
//这里通过构造方法注入
private SqlSessionFactory sqlSessionFactory;
public UserDaoImpl(SqlSessionFactory sqlSessionFactory){
this.sqlSessionFactory = sqlSessionFactory;
}
public User findUserById(int id) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = sqlSession.selectOne("test.findUserById",id);
sqlSession.close();
return user;
}
public void insertUser(User user) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.insert("test.insertUser",user);
sqlSession.commit();
sqlSession.close();
}
public void deleteUser(int id) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.delete("test.deleteUser",id);
sqlSession.commit();
sqlSession.close();
}
}
3 UserDaoImplTest.java
import dao.UserDao;
import dao.impl.UserDaoImpl;
import entity.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;
import java.util.Date;
public class UserDaoImplTest {
private SqlSessionFactory sqlSessionFactory;
//测试前执行
@Before
public void setUp() throws IOException {
//配置文件
String resource = "SqlMapConfig.xml";
//的到配置文件流
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建会话工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void testFinUserById() throws Exception {
UserDao userDao = new UserDaoImpl(sqlSessionFactory);
User user = userDao.findUserById(1);
System.out.println(user);
}
@Test
public void insertUser() throws Exception{
UserDao userDao = new UserDaoImpl(sqlSessionFactory);
User user1 = new User();
user1.setUsername("王麻子");
user1.setBirthday(new Date());
user1.setSex("女");
user1.setAddress("日本东京");
userDao.insertUser(user1);
}
@Test
public void deleteUser() throws Exception{
UserDao userDao = new UserDaoImpl(sqlSessionFactory);
userDao.deleteUser(13);
}
}
三 mybatis开发dao方法-mapper代理开发方法-程序员只需要mapper接口(相当于dao接口)
- 程序员不在需要编写dao接口的实现
- 程序员需要编写mapper.xml映射文件,编写时遵循一些开发规范,mybatis可以自动生成mapper接口类代理对象
1 开发规范
(1)在mapper.xml中namespace等于mapper接口地址
(2)mapper.java接口中的方法名和mapper.xml中statement的id一致
(3)mapper.java接口中的方法输入类型和mapper.xml中statement的parameterType指定的类型一致
(4)mapper.java接口中方法返回值类型和mapper.xml中statement的resultType指定的类型一致
2 UserDaoMapper.java
package dao;
import entity.User;
public interface UserDaoMapper {
//根据id查询
public User findUserById(int id) throws Exception;
//插入用户
public void insertUser(User user) throws Exception;
//删除用户
public void deleteUser(int id) throws Exception;
//修改用户信息
public void updateUser(User user) throws Exception;
}
3 userMapper.xml
<?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">
<!--namespace命名空间,作用就是对sql进行分类化管理,区分不同的sql空间
注意:使用mapper代理方法开发,namespace有特殊重要作用-->
<mapper namespace="dao.UserDaoMapper">
<!--在映射文件中配置很多sql语句-->
<!-- 需求:通过id查询用户表的记录-->
<!-- 通过select执行数据库查询
id:标识映射文件中sql,将sql语句封装到mappedStatement对象中,所以将id称为statement的id
parameterType:指定输入参数的类型,这里指定int型
resultType:指定sql输出结果所映射的java对象类型
#{ }表示一个占位符
#{id}:其中的id表示接收输入的参数,参数名称就是id-->
<select id="findUserById" parameterType="int" resultType="entity.User">
SELECT * FROM user WHERE id = #{id}
</select>
<!--根据用户名称模糊查询信息-->
<!--可能返回多条信息
${}:表示拼接sql串,将接收到的参数的内容不加任何修饰拼接在sql中
使用${}拼接sql,引起sql注入
${value}:接收输入参数的内容,如果出入类型是简单类型,${}只能使用value-->
<select id="findUserByName" parameterType="String" resultType="entity.User">
SELECT * FROM user WHERE username LIKE "${value}%"
</select>
<!--添加用户-->
<insert id="insertUser" parameterType="entity.User">
<!--将插入数据的主键返回
SELECT Last_insert_ID 得到刚插入的主键值 只适用与自增主键
keyProperty :将查询到主键值设置到parameterType指定的对象的那个属性
order:SELECT Last_insert_ID执行顺序,相对于insert语句来说它的执行顺序
resultType:指定SELECT LAST_INSERT_ID()的结果类型
-->
<selectKey keyProperty="id" order="AFTER" resultType="int">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO user (username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})
</insert>
<!--删除用户 通过id-->
<delete id="deleteUser" parameterType="int">
DELETE from user where id = #{id}
</delete>
<!--修改用户信息 根据id-->
<update id="updateUser" parameterType="entity.User">
UPDATE user SET username = #{username},birthday = #{birthday},sex = #{sex},address = #{address} WHERE id = #{id}
</update>
</mapper>
4 UserDaoMapperTest
import dao.UserDaoMapper;
import entity.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;
public class UserDaoMapperTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void setUp() throws IOException{
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void findUserById() throws Exception{
SqlSession sqlSession= sqlSessionFactory.openSession();
//创建UserMapper对象,mybatis自动生成mapper代理对象
UserDaoMapper userDaoMapper = sqlSession.getMapper(UserDaoMapper.class);
//调用usermapper对象
User user = userDaoMapper.findUserById(10);
System.out.println(user);
}
@Test
public void insertUserd() throws Exception{
SqlSession sqlSession= sqlSessionFactory.openSession();
//创建UserMapper对象,mybatis自动生成mapper代理对象
UserDaoMapper userDaoMapper = sqlSession.getMapper(UserDaoMapper.class);
//调用usermapper对象
User user = new User();
user.setUsername("短毛");
user.setBirthday(new Date());
user.setSex("女");
user.setAddress("德国柏林");
userDaoMapper.insertUser(user);
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserDaoMapper userDaoMapper = sqlSession.getMapper(UserDaoMapper.class);
userDaoMapper.deleteUser(13);
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUser() throws Exception{
SqlSession sqlSession = sqlSessionFactory.openSession();
UserDaoMapper userDaoMapper = sqlSession.getMapper(UserDaoMapper.class);
User user = new User();
user.setId(12);
user.setUsername("短毛");
user.setBirthday(new Date());
user.setSex("女");
user.setAddress("德国柏林");
userDaoMapper.updateUser(user);
sqlSession.commit();
sqlSession.close();
}
}