接下来我们把配置信息罗列一下
主配置文件:SqlMapConfig.xml
<?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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/demo" /> <property name="username" value="root" /> <property name="password" value="123" /> </dataSource> </environment> </environments> <!-- 加载映射文件 --> <mappers> <mapper resource="com/demo/entity/EmpMapper.xml" /> </mappers> </configuration>
EmpMapper.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"> <mapper namespace="com.demo.entity.emp"> <select id="findbyid" resultType="com.demo.entity.emp"> select * from emp </select> </mapper>
接下来是写一个Test来测验一下,因为此次只是测试session的创建,所一并未执行查询语句。
package com.demo.entity; import java.io.InputStream; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class Test { public static void main(String []args){ String resource="config.xml"; //获得输入流 InputStream inputStream= Test.class.getClassLoader() .getResourceAsStream(resource); //获得SqlSessionFactoryBuilder对象 SqlSessionFactoryBuilder builder= new SqlSessionFactoryBuilder(); //获得SqlSessionFactory SqlSessionFactory factory=builder.build(inputStream); //获得session SqlSession session = factory.openSession(); System.out.println("success!"); session.close(); } }
控制台输出:
success!
这里我们可以做一些简单的封装,可以做一个对SqlSession返回对象的一个封装。废话不多说,直接上code:
package com.demo.Utils; import java.io.InputStream; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MybatisUtil { public static SqlSession getSqlSession(){ String resource = "SqlMapConfig.xml"; InputStream is = MybatisUtil.class.getClassLoader().getResourceAsStream(resource); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession session = sessionFactory.openSession(); return session; } }
这样一个Utils就完成了,如果以后需要获取SqlSession对象,直接调用就好了。
然后写一个Test:
package Test; import org.apache.ibatis.session.SqlSession; import com.demo.Utils.MybatisUtil; public class TestEmp { public static void main(String[] args){ SqlSession session = MybatisUtil.getSqlSession(); System.out.println("use session "); session.close(); } }
控制台输出:
use session
这样我们就获取到了SqlSession对象。
版权声明:本文为博主原创文章,如需转载请表明出处。 https://blog.csdn.net/qq_39266910/article/details/77839546