赞
踩
在Mybatis中SqlSesion
提供了在数据库执行SQL命令所需的所有方法。可以通过SqlSessionFactory
对象直接获取一个SqlSession
.
mybatis-config.xml
文件中配置DataSource<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties> <property name="datasource.driver" value="com.mysql.cj.jdbc.Driver"/> <property name="datasource.url" value="jdbc:mysql://localhost:3306/spring"/> <property name="datasource.username" value="root"/> <property name="datasource.password" value="123456"/> </properties> <!--尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境--> <environments default="dev"> <environment id="dev"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${datasource.driver}"/> <property name="url" value="${datasource.url}"/> <property name="username" value="${datasource.username}"/> <property name="password" value="${datasource.password}"/> </dataSource> </environment> </environments> <mappers> <!-- 使用相对于类路径的资源引用 --> <mapper resource="mapper/UserMapper.xml"/> </mappers> </configuration>
package com.tyler.mybatis.service; import com.tyler.mybatis.domain.User; import com.tyler.mybatis.mapper.UserMapper; 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.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import static org.junit.jupiter.api.Assertions.assertEquals; public class BasicTestDemo { private static SqlSession sqlSession; @BeforeAll static void setup() throws IOException { InputStream resource = Resources.getResourceAsStream("config/mybatis-config.xml"); // 创建SqlSessionFactory对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resource); // 获取SqlSession 实例 sqlSession = sqlSessionFactory.openSession(); } }
@Test void testSqlSession(){ // 这里的第一个参数是我们定义的Mapper 接口的全限定名+对应的方法,第二个参数是方法对应的参数 User user = sqlSession.selectOne("com.tyler.mybatis.mapper.UserMapper.selectUser", 1); assertEquals("Tyler", user.getName()); } /** * 也可以通过SqlSession获取到对应的Mapper接口,然后再调用对应的方法 */ @Test void testSession(){ UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.selectUser(3); assertEquals("Silver", user.getName()); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。