package org.rain.mybatis.utils;
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;
/**
* @author liaojy
* @date 2023/5/19 - 7:41
*/
public class SqlSessionUtils {
public static SqlSession getSqlSession(){
SqlSession sqlSession = null;
try {
//读取MyBatis核心配置文件的输入流
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//通过核心配置文件所对应的字节输入流创建工厂类SqlSessionFactory,用于生产SqlSession对象
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//创建自动提交事务的SqlSession对象
sqlSession = sqlSessionFactory.openSession(true);
} catch (IOException e) {
e.printStackTrace();
}
return sqlSession;
}
}
void updateUser();
<!--void updateUser();-->
<update id="updateUser">
update t_user set username='root',password='123' where id = 3
</update>
@Test
public void testUpdate(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.updateUser();
sqlSession.close();
}
-----------------------------------分割线-----------------------------------
void deleteUser();
<!--void deleteUser();-->
<delete id="deleteUser">
delete from t_user where id = 2
</delete>
@Test
public void testDelete(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.deleteUser();
sqlSession.close();
}
-----------------------------------分割线----------------------------------
User getUserById();
注意:
查询的标签select必须设置属性resultType或resultMap,用于设置实体类和数据库表的映射关系
resultType:自动映射,设置查询结果要转换为的Java类型,用于属性名和字段名一致的情况
resultMap:自定义映射,用于一对多或多对一,或用于字段名和属性名不一致的情况
<!--User getUserById();-->
<select id="getUserById" resultType="org.rain.mybatis.pojo.User">
select * from t_user where id = 3
</select>
@Test
public void testGetUserById(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById();
System.out.println(user);
sqlSession.close();
}
List<User> getAllUser();
<!--List<User> getAllUser();-->
<select id="getAllUser" resultType="org.rain.mybatis.pojo.User">
select * from t_user
</select>
@Test
public void testGetAllUser(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> allUser = userMapper.getAllUser();
for (User user : allUser) {
System.out.println(user);
}
sqlSession.close();
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章