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)数据库设计如下
单纯插入数据
(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.