在这里《mybatis基本操作(一)》我介绍了mybatis使用配置文件对数据库进行增删改查。下面将介绍mybatis使用注解进行相应的操作。首先,使用注解同样要配置总配置文件,JavaBean,以及properties文件。只是将(一)中的student.xml文件替换为studentMapper.java。如下:
1 package com.zhouxy.ibatis; 2 3 import java.util.List; 4 5 import org.apache.ibatis.annotations.Delete; 6 import org.apache.ibatis.annotations.Insert; 7 import org.apache.ibatis.annotations.Select; 8 import org.apache.ibatis.annotations.Update; 9 10 11 /** 12 * studentMapper.java是一个接口.在接口中将sql语句传入相应的注解中。 13 * @author zhouxy 14 * 15 */ 16 public interface StudentMapper { 17 18 @Select("select * from student") 19 public List<Student> getAllStudents(); 20 21 @Select("select * from student where id = #{id}") 22 public Student getStudentById(int id); 23 24 @Select("select * from student where name like \"%\"#{name}\"%\"") 25 public List<Student> getStudentByName(String name); 26 27 @Insert("insert into student(name,age) values(#{name},#{age})") 28 public void addStudent(Student student); 29 30 @Update("update student set name = #{name},age=#{age}") 31 public void updateStudent(Student student); 32 33 @Delete("delete from student where id = #{id}") 34 public void deleteStudentById(int id); 35 }
上面编写了StudentMapper,它相当于使用配置文件中的student.xml文件。下面是对StudentMapper进行注册,返回获得了sqlsession对象的studentMapper对象:
1 package com.zhouxy.ibatis; 2 3 import java.util.List; 4 5 import org.apache.ibatis.session.SqlSession; 6 import org.apache.ibatis.session.SqlSessionFactory; 7 8 public class StudentDaoByAnnotation { 9 //得到studentMapper对象,就像使用配置文件要获取SqlSession对象一样. 10 public static StudentMapper getStudentMapper(){ 11 StudentMapper studentMapper = null; 12 SqlSessionFactory sqlSessionFactory = SessionFactoryUtils.getSqlSessionFactory(); 13 14 sqlSessionFactory.getConfiguration().addMapper(StudentMapper.class);//必须注册StudentMapper 15 16 SqlSession sqlSession = sqlSessionFactory.openSession(); 17 studentMapper = sqlSession.getMapper(StudentMapper.class); 18 19 return studentMapper; 20 } 21 }
测试:
1 package com.zhouxy.ibatis; 2 3 public class TestMapper { 4 //获得指定学生 5 public static void getStudentById(int id){ 6 StudentMapper studentMapper = StudentDaoByAnnotation.getStudentMapper(); 7 Student student = studentMapper.getStudentById(id); 8 9 System.out.println(student.toString()); 10 } 11 12 public static void main(String[] args) { 13 getStudentById(8); 14 } 15 }
测试结果:
这两种方式在不同的情况下使用不同的方式会带来各自的好处,可以择优选取。
时间: 2024-10-25 17:50:24