MyBatis的CURD操作(Dao接口实现类)

本文详细介绍了MyBatis中自定义Dao接口实现类进行CURD操作的步骤,包括插入、更新、删除、查询(返回List和Map)、模糊查询等,并讲解了$与#的区别以及如何处理属性名与查询字段名不一致的情况。示例涵盖了从实体类、Dao接口、Dao实现类到测试类的完整流程。
摘要由CSDN通过智能技术生成

CURD 操作,即指对数据库中实体对象的增 Create、改 Update、查 Read、删 Delete 操作。

自定义 Dao 接口实现类

项目实例

(1)定义实体类

public class Student {
   
	private Integer id;
	private String name;
	private int age;
	private double score;

(2)定义 Dao 接口

public interface IStudentDao {
   
	void insertStudent(Student student);
	void insertStudentCacheId(Student student);
	
	void deleteStudentById(int id);
	void updateStudent(Student student);
	
	List<Student> selectAllStudents();
	Map<String, Student> selectStudentMap();
	
	Student selectStudentById(int id);
	Student selectStudentById(Map<String, Object> map);
	
	List<Student> selectStudentsByName(String name);

}

(3)定义 Dao 实现类

public class StudentDaoImpl implements IStudentDao {
   
	
	private SqlSession sqlSession;

	@Override
	public void insertStudent(Student student) {
   
		try {
   
			//使用工具类获取SqlSession对象
			sqlSession = MyBatisUtil.getSqlSession();
			//操作
			sqlSession.insert("insertStudent",student);
			//SqlSession提交
			sqlSession.commit();
		} finally {
   
			//SqlSession关闭,添加了close()不用作事务回滚
			if (sqlSession != null) 
				sqlSession.close();
			
		}
		
	}

(4)创建工具类

public class MyBatisUtil {
   
	private static SqlSessionFactory sqlSessionFactory;

	public static SqlSession getSqlSession() {
   
		try {
   
			InputStream is = Resources.getResourceAsStream("mybatis.xml");
			if (sqlSessionFactory == null) {
   
				sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
			}
			return sqlSessionFactory.openSession();
		} catch (IOException e) {
   
			e.printStackTrace();
		}
		return null;
	}

}

(5)定义测试类

public class MyTest {
   
	private StudentDaoImpl dao;
	
	@Before
	public void setUp() {
   
		dao= new StudentDaoImpl();
	}

}

(6)数据库设计如下

{% asset_img curd01.jpg %}

单纯插入数据

(1)修改映射文件

	<insert id="insertStudent"
	parameterType="com.huang.beans.Student">
		insert into 
		student(name,age,score) 
		values(#{name},#{age}, #{score})
	</insert>
  • id:该 SQL 语句的唯一标识, Java 代码中要使用该标识
  • #{ }:对指定参数类型属性值的引用。其底层是通过反射机制,调用 Student 类相关属性的 get 方法来获取值的。因为底层使用的是反射,所以这里使用的是类的属性名,而非表的字段名。

(2)修改 Dao 实现类

使用 SqlSession 对象的 insert()方法。该方法默认返回 DB 中受影响条数。其方法原型为:insert(String id, Object obj)。

@Override
	public void insertStudent(Student student) {
   
		try {
   
			//使用工具类获取SqlSession对象
			sqlSession = MyBatisUtil.getSqlSession();
			//操作
			sqlSession.insert("insertStudent",student);
			//SqlSession提交
			sqlSession.commit();
		} finally {
   
			//SqlSession关闭,添加了close()不用作事务回滚
			if (sqlSession != null) {
   
				sqlSession.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值