标题mybatis项目搭建注意事项
<?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/mysql"/>
<property name="username" value="root"/>
<property name="password" value="Lyy@2021"/>
</dataSource>
</environment>
</environments>
<mappers>
//resource复制即可,mapper文件目录要与mapper接口目录保持一致
<!-- <mapper resource="com.lina.demo.mapper.EmpMapper.xml"/>-->
<mapper resource="com.lina/mapper/EmpMapper.xml"/>
</mappers>
</configuration>
public class Test1 {
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
return sqlSessionFactory;
}
@Test
public void test() throws IOException {
//1.获取一个SqlSessionFactory对象
String resource = "mybatis.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.使用一个SqlSessionFactory对象open一个SqlSession对象
SqlSession session = sqlSessionFactory.openSession();
try {
Emp emp = (Emp) session.selectOne("com.lina.mapper.EmpMapper.selectEmp", 1);
System.out.println(emp);
} finally {
//4.关闭sqlSession
session.close();
}
}
}