关于mybatis配置环境问题
1.resources文件下配置(mybatis_congig.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/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--每一个mapper.xml都需要在mybatis核心配置文件中 注册-->
<mappers>
<mapper resource="com/muzi/Dao/UserMapper.xml"/>
</mappers>
</configuration>
2.在src下创建三级包mybatisUtils:
package com.muzi.Untils;
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 MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//第一步//获取sqlSessionFactory
String resource= "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//获取 SqlSession
public static SqlSession getSqlSession (){
/*SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;*/
/*简化为*/
return sqlSessionFactory.openSession();
}
}
3.在dao层创建usermapper映射接口和uermapper.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绑定一个对应的Dao/mapper接口-->
<mapper namespace="com.muzi.Dao.UserMapper">
<!--select 查询语句-->
<select id="getUserList" resultType="com.muzi.entity.User">
select * from User
</select>
-
UserMapper.java
package com.muzi.Dao; import com.muzi.entity.User; import java.util.List; public interface UserMapper { //查询全部用户 List<User> getUserList();
4.最后编写测试类(test测试需对应实体包):
Test测试类:
package com.muzi.Dao;
import com.muzi.Untils.MybatisUtils;
import com.muzi.entity.User;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/*
增删改需要提交事务(注意)
*/
public class UserTest{
@Test
public void test(){
//获取SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//执行sql
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭资源
sqlSession.close();
}