myBatis-conf.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>
<!--自定义别名-->
<typeAliases>
<typeAlias type="com.xxjqr.crud.User" alias="User"/>
</typeAliases>
<!--可以设置多个运行环境,满足不同需要,例如 开发、测试、生产环境上有不同一配置 -->
<environments default="development"><!-- default表示当前使用的配置环境 -->
<environment id="development">
<!--事务管理类型主要有jdbc和managed,前者依赖于数据源获得的连接,后者依赖于容器 -->
<transactionManager type="JDBC" />
<!-- 配置数据库连接信息 POOLED表示使用连接池,UNPOOLED表示不使用连接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis01" />
<property name="username" value="root" />
<property name="password" value="221121" />
</dataSource>
</environment>
</environments>
<!-- 加入映射文件信息 -->
<mappers>
<!-- 注意:是/不是.-->
<mapper resource="com/xxjqr/crud/userMapper.xml"/>
</mappers>
</configuration>
userMapper.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.xxjqr.crud.userMapper">
<resultMap type="User" id="userResultMap">
<id column="user_id" property="userId"/>
<result column="user_name" property="userName"/>
<result column="user_age" property="userAge"/>
</resultMap>
<!-- 定位:namespace+id -->
<insert id="insertUser" parameterType="User">
insert into user_t(user_name,user_age) values(#{userName},#{userAge})
</insert>
<update id="updateUser" parameterType="user">
update user_t set user_name=#{userName},user_age=#{userAge}
where user_id = #{userId}
</update>
<delete id="deleteUser" parameterType="integer" >
delete from user_t where user_id = #{id}<!-- 传入的参数不是对象类型,所以变量名可以随意 -->
</delete>
<!-- 查询单个用户信息 -->
<select id="selectUser" parameterType="integer" resultMap="userResultMap" >
select user_id,user_name,user_age from user_t where user_id = #{id}
</select>
<!-- 根据姓名查询多个用户信息 -->
<!-- 如果返回的是list,resultMap指定的值是list集合里元素的类型-->
<select id="selectList" parameterType="string" resultMap="userResultMap" >
select user_id,user_name,user_age from user_t where user_name like #{name}
</select>
</mapper>
类
@Data
public class User {
private int userId;
private String userName;
private int userAge;
}
public class UserDao {
SqlSession session = null;
//保存用户信息
public int save(User user){
int i =0;
try {
session = MybatisSessionFactory.getSession();
//执行数据处理,第一个参数用“命名空间+sql id"来定位sql,第二个参数用来给sql传参数
i = session.insert("com.xxjqr.crud.userMapper.insertUser", user);
//提交事务
session.commit();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}finally{
try {
MybatisSessionFactory.closeSession();
} catch (Exception e) {
e.printStackTrace();
}
}
return i;
}
//根据用户id更新用户信息
public int update(User user){
int i = 0 ;
try {
session=MybatisSessionFactory.getSession();
i = session.update("com.xxjqr.crud.userMapper.updateUser",user);
session.commit();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}finally{
try {
MybatisSessionFactory.closeSession();
} catch (Exception e) {
e.printStackTrace();
}
}
return i;
}
//根据id删除用户信息
public int delete(Integer id){
int i = 0 ;
try {
session=MybatisSessionFactory.getSession();
i = session.delete("com.xxjqr.crud.userMapper.deleteUser",id);
session.commit();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}finally{
try {
MybatisSessionFactory.closeSession();
} catch (Exception e) {
e.printStackTrace();
}
}
return i;
}
//根据id查找用户信息
public User selectOne(Integer id){
User user =null;
try {
session=MybatisSessionFactory.getSession();
user = session.selectOne("com.xxjqr.crud.userMapper.selectUser",id);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
MybatisSessionFactory.closeSession();
} catch (Exception e) {
e.printStackTrace();
}
}
return user;
}
//根据姓名查找用户信息
public List<User> selectList(String name){
List<User> users =null;
try {
session=MybatisSessionFactory.getSession();
users = session.selectList("com.xxjqr.crud.userMapper.selectList",name);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
MybatisSessionFactory.closeSession();
} catch (Exception e) {
e.printStackTrace();
}
}
return users;
}
}
public class TestUserDao {
private UserDao userDao = new UserDao();
@Test
public void test() {
int i = 0;
//保存操作
// User user = new User();
// user.setUserName("丁昌江2");
// user.setUserAge(22);
// i = userDao.save(user);
//删除操作
// i = userDao.delete(14);
//
//更新操作
// user.setUserId(1);
// user.setUserName("张无忌");
// user.setUserAge(111);
// i =userDao.update(user);
// System.out.println("受影响行数:"+i);
//查询操作(单个)
// User user = userDao.selectOne(1);
// System.out.println(user);
//查询操作(多个)
List<User> list = userDao.selectList("丁昌江%");
System.out.println(list);
}
}
public class MybatisSessionFactory {
private static final ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
private static SqlSessionFactory sessionFactory;
private static String CONFIG_FILE_LOCATION = "myBatis-config.xml";
static {
buildSessionFactory();
}
private MybatisSessionFactory() {
}
/**获取session*/
public static SqlSession getSession() throws Exception {
SqlSession session = (SqlSession) threadLocal.get();
if (session == null ) {
if (sessionFactory == null) {
buildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**构建session工厂*/
private static void buildSessionFactory() {
Reader reader =null;
try {
reader = Resources.getResourceAsReader(CONFIG_FILE_LOCATION);
sessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}finally{
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**关闭session*/
public static void closeSession() throws Exception {
SqlSession session = (SqlSession) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
}
/*
* 该工具类是线程安全的:
* threadLocal.set(session)相当于是
* threadLocal.put(threadLocal.currentThead,session)
*
* threadLocal.get()相当于是
* threadLocal.get(threadLocal.currentThead)
* */