【学习笔记】Mybatis的使用
-
创建项目,导入依赖
mysql-connector-java mysql驱动依赖 mybatis mybatis依赖
至少要导入这两个依赖
-
编写SqlSessionFactory 工具类
package utils; 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 java.io.IOException; import java.io.InputStream; public class SqlSessionUtils { private static SqlSessionFactory sqlSessionFactory; static{ try { String resource = "mybatis-config.xml"; InputStream is = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
resource 是 mabatis配置文件,通过Resources类把这个文件变成流
然后实例化一个 SqlSessionFactoryBuilder 对象,调用 build() 方法,获得SqlSessionFactory实例
还可以顺带将 调用openSession() 封装到工具类中变成一个方法 getSqlSession()
sqlSessionFactory.openSession() 的意义就是通过工厂获得 SqlSession 的实例
不难发现在这段代码中,我们需要一个mabatis-config.xml 配置文件
-
编写 mabatis-config.xml 配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "https://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf-8&useSSL=false"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="Dao/UserDao.xml"/> </mappers> </configuration>
XML配置文件中包含了对mybatis系统的核心配置,包括获取数据库连接实例的数据源(dataSource),以及决定事务作用域和控制方式的事务管理器(transactionManager)
还有有关于sql语句的xml的配置
<mappers>
<mapper resource="Dao/UserDao.xml"/>
</mappers>
-
编写持久层接口及其配置文件xml
接口:
package Dao; import pojo.User; import java.util.List; public interface UserDao { List<User> getUsers(); Boolean insertUser(); }
xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="Dao.UserDao"> <select id="getUsers" resultType="pojo.User"> select * from jdbcstudy.users; </select> <insert id="insertUser" > insert into jdbcstudy.users(id,`NAME`,`PASSWORD`,email,birthday) values(7,'阿三','145263','asan@qq.com','2000-02-02') </insert> </mapper>
mapper 标签中的 namespace 绑定了持久层接口,注意要写完整的路径
查询语句 就用 select标签,增删改都有对应的标签
select 标签中 的 id 就是接口中的方法名 resultType是查询语句的返回值类型,如果是集合就写集合中的泛型
-
测试
import Dao.UserDao; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import pojo.User; import utils.SqlSessionUtils; import java.util.List; public class UserDaoTest { @Test public void test(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); Boolean aBoolean = mapper.insertUser(); System.out.println("是否执行成功"+ aBoolean); List<User> users = mapper.getUsers(); for (User user: users) { System.out.println(user.toString()); } sqlSession.close(); } }
先调用SqlSessionFactory 工具类获得 SqlSession,然后调用SqlSession的getMapper()方法,参数就是接口的class,返回值是接口类型的 对象
然后直接用这个对象调用 接口中的方法即可
增删改,需要提交事务
删除:
public interface UserDao {
int deleteUser(int id);
}
<delete id="deleteUser">
delete from jdbcstudy.users where id = #{id}
</delete>
@Test
public void testDelete(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
mapper.deleteUser(5);
sqlSession.commit();
sqlSession.close();
}
添加一条记录:
//添加一条记录
int intsertOneCity(City city);
<insert id="insertOneCity" parameterType="com.wang.pojo.City">
insert into jdbcstudy.city(id,cityname,person) values(#{id},#{cityname},#{person})
</insert>
public void test03(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
CityMapper mapper = sqlSession.getMapper(CityMapper.class);
int i = mapper.insertCity(new City(6, "青岛", 600));
//sqlSession.commit();
sqlSession.close();
}
添加多条记录:
在xml文件中使用foreach标签
//添加多个城市
int insertCity(List<City> city);
<insert id="insertCity" parameterType="com.wang.pojo.City">
insert into jdbcstudy.city(id,cityname,person) values
<foreach collection="list" item="citys" separator=",">
(#{citys.id},#{citys.cityname},#{citys.person})
</foreach>
</insert>
public void test03(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
CityMapper mapper = sqlSession.getMapper(CityMapper.class);
List<City> citys = new ArrayList<>();
City city1 = new City(6, "青岛", 600);
City city2 = new City(7, "济南", 600);
citys.add(city1);
citys.add(city2);
int i = mapper.insertCity(citys);
//sqlSession.commit();
sqlSession.close();
}
如果涉及到了增删改的情况,需要在执行了接口中的方法后,sqlSession.commit() 提交事务
否则在数据库表中并没有什么改变。
如果不想手动提交事务,可以设置为自动提交事务
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}