Mybatis是輕量級的持久化框架,的確上手非常快. Mybatis大體上的思路就是由一個總的config文件配置全局的信息,比如mysql連接信息等。然後再mapper中指定查詢的sql,以及參數和返回值。 在Service中直接調用這個mapper即可。 依賴的jar包 主要的mybatis配置 ...
Mybatis是輕量級的持久化框架,的確上手非常快.
Mybatis大體上的思路就是由一個總的config文件配置全局的信息,比如mysql連接信息等。然後再mapper中指定查詢的sql,以及參數和返回值。
在Service中直接調用這個mapper即可。
依賴的jar包
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
</dependency>
主要的mybatis配置文件
<?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 alias="Student" type="mybatis.Student"/>
</typeAliases>
<!-- 配置mysql連接 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://192.168.56.101:3306/mysql"/>
<property name="username" value="root"/>
<property name="password" value="123qwe"/>
</dataSource>
</environment>
</environments>
<!-- 配置mapper -->
<mappers>
<mapper resource="StudentMapper.xml"/>
</mappers>
</configuration>
創建SqlSession工廠
public class MyBatisSqlSessionFactory {
private static SqlSessionFactory sqlSessionFactory;
public static SqlSessionFactory getSqlSessionFactory(){
if(sqlSessionFactory == null){
InputStream inputStream;
try{
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e){
System.out.println(e.getMessage());
}
}
return sqlSessionFactory;
}
public static SqlSession openSession(){
return getSqlSessionFactory().openSession();
}
}
創建Student類:
public class Student {
private Integer studId;
private String name;
private String email;
private Date dob;
public Integer getStudId() {
return studId;
}
public void setStudId(Integer studId) {
this.studId = studId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
}
創建Mapper配置文件
<?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="mybatis.StudentMapper">
<resultMap type="Student" id="StudentResult">
<id property="studId" column="stud_id"/>
<result property="name" column="name"/>
<result property="email" column="email"/>
<result property="dob" column="dob"/>
</resultMap>
<select id="findAllStudents" resultMap="StudentResult">
SELECT * FROM STUDENTS
</select>
<select id="findStudentById" parameterType="int" resultType="Student">
SELECT STUD_ID AS STUDID,NAME,EMAIL,DOB FROM STUDENTS WHERE STUD_ID=#{ID}
</select>
<insert id="insertStudent" parameterType="Student">
INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(#{studId},#{name},#{email},#{dob})
</insert>
</mapper>
創建Mapper介面
public interface StudentMapper {
List<Student> findAllStudents();
Student findStudentById(Integer id);
void insertStudent(Student student);
}
創建服務類和測試類
public class StudentService {
public List<Student> findAllStudents(){
SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
try{
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.findAllStudents();
}finally {
sqlSession.close();
}
}
public Student findStudentById(Integer studId){
SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.findStudentById(studId);
}finally {
sqlSession.close();
}
}
public void createStudent(Student student){
SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
try{
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
studentMapper.insertStudent(student);
sqlSession.commit();
}finally {
sqlSession.close();
}
}
}
單元測試類
public class StudentServiceTest {
private static StudentService studentService;
@BeforeClass
public static void setup(){
studentService = new mybatis.StudentService();
}
@AfterClass
public static void teardown(){
studentService = null;
}
@Test
public void testFindAllStudents(){
List<Student> students = studentService.findAllStudents();
Assert.assertNotNull(students);
for(Student student:students){
System.out.println(student);
}
}
@Test
public void testFindStudentById(){
Student student = studentService.findStudentById(1);
Assert.assertNotNull(student);
System.out.println(student);
}
@Test
public void testCreateStudent(){
Student student = new Student();
student.setStudId(3);
student.setName("student_"+3);
student.setEmail("student_"+3+"@email.com");
student.setDob(new Date());
studentService.createStudent(student);
Student newStudent = studentService.findStudentById(3);
Assert.assertNotNull(newStudent);
}
}
資料庫腳本
create table STUDENTS(
stud_id int(11) not null auto_increment,
name varchar(50) not null,
email varchar(50) not null,
dob date default null,
primary key(stud_id)
);
insert into STUDENTS(stud_id,name,email,dob) values(1,"student1","[email protected]","1999-08-08");
insert into STUDENTS(stud_id,name,email,dob) values(2,"student2","[email protected]","2000-01-01");
select * from STUDENTS;