MyBatis初学

MyBatis 初学笔记

Student.java

package com.xiejiaohui.domain;

import java.util.Date;

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;
	}
}

 StudentMapper.java

package com.xiejiaohui.mappers;

import java.util.List;

import org.apache.ibatis.session.RowBounds;

import com.xiejiaohui.domain.Student;

public interface StudentMapper {
    
    List<Student> findAllStudents();
    
    List<Student> findAllStudents(RowBounds rowBounds);

    Student findStudentById(Integer id);

    void insertStudent(Student student);
    
    int deleteAllStudents();
    
    int countAllStudents();

}

StudentMapper.xml

<?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="com.xiejiaohui.mappers.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>

<delete id="deleteAllStudents" parameterType="int">
	delete from students
</delete>

<select id="countAllStudents" resultType="int">
	select count(*) from students
</select>

</mapper>

 StudentService.java

package com.xiejiaohui.services;

import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xiejiaohui.domain.Student;
import com.xiejiaohui.mappers.StudentMapper;
import com.xiejiaohui.util.MyBatisSqlSessionFactory;

public class StudentService {

	private Logger logger = LoggerFactory.getLogger(getClass());

	public List<Student> findAllStudents() {
		SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
		try {
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			return studentMapper.findAllStudents();
		} finally {
			sqlSession.close();
		}
	}
	
	/**
	 * 采用分页的方式来查询
	 */
	public List<Student> findAllStudents2() {
		int offset = 0, limit = 10;
		RowBounds rowBounds = new RowBounds(offset, limit);
		SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
		try {
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			return studentMapper.findAllStudents(rowBounds);
		} finally {
			sqlSession.close();
		}
	}

	public Student findStudentById(Integer studId) {
		logger.debug("Select Student By ID: {}", studId);
		SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
		try {
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			return studentMapper.findStudentById(studId);
		} finally {
			sqlSession.close();
		}
	}

	public Student findStudentById2(Integer studId) {
		SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
		try {
			Student student = (Student) sqlSession.selectOne("com.xiejiaohui.mappers.StudentMapper.findStudentById",
					studId);
			return student;
		} 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 int deleteAllStudents() {
		SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
		try {
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			int i = studentMapper.deleteAllStudents();
			sqlSession.commit();
			return i;
		} finally {
			sqlSession.close();
		}
	}
	
	public int countAllStudents() {
		SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
		try {
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			int i = studentMapper.countAllStudents();
			return i;
		} finally {
			sqlSession.close();
		}
	}

}

 StudentServiceTest.java

package com.xiejiaohui.services;

import java.util.Date;
import java.util.List;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import com.xiejiaohui.domain.Student;

public class StudentServiceTest {

	private static StudentService studentService;

	@BeforeClass
	public static void setup() {
		studentService = new StudentService();
	}

	@AfterClass
	public static void teardown() {
		studentService = null;
	}
	
	@Test
	public void testCreateStudent() {
		for (int i = 1; i <= 100; i++) {
			Student student = new Student();
			int id = i;
			student.setStudId(id);
			student.setName("student_" + id);
			student.setEmail("student_" + id + "@gmail.com");
			student.setDob(new Date());
			studentService.createStudent(student);
			Student newStudent = studentService.findStudentById(id);
			Assert.assertNotNull(newStudent);
		}
	}

	@Test
	public void testFindAllStudents() {
		List<Student> students = studentService.findAllStudents();
		Assert.assertNotNull(students);
		for (Student student : students) {
			System.out.println(student);
		}
	}
	
	@Test
	public void testFindAllStudents2() {
		List<Student> students = studentService.findAllStudents2();
		Assert.assertNotNull(students);
		for (Student student : students) {
			System.out.println("......" + student.getName());
		}
	}

	@Test
	public void testFindStudentById() {
		Student student = studentService.findStudentById(1);
		Assert.assertNotNull(student);
		System.out.println(student);
	}
	
	@Test
	public void testFindStudentById2() {
		Student student = studentService.findStudentById2(1);
		Assert.assertNotNull(student);
		System.out.println(student);
	}
	
	@Test
	public void testDeleteAllStudents() {
		int begin = studentService.countAllStudents();
		int end = studentService.deleteAllStudents();
		Assert.assertEquals(end, begin);
		System.out.println("begin: " + begin + " end: " + end);
	}
	
//	create table students(stud_id int(11) not null auto_increment, name varch
//			ar(50) not null, email varchar(50) not null, dob date default null, primary key
//			(stud_id));

}

 MyBatisSqlSessionFactory.java

package com.xiejiaohui.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

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) {
				throw new RuntimeException(e.getCause());
			}
		}
		return sqlSessionFactory;
	}
	
	public static SqlSession openSession() {
		return getSqlSessionFactory().openSession();
	}
}

 MyBatisUtil.java

package com.xiejiaohui.util;

import org.apache.ibatis.session.SqlSession;

public class MyBatisUtil {

	public static SqlSession openSession() {
		
		return MyBatisSqlSessionFactory.openSession();
		
	}

}

 log4j.properties

log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n

mybatis-config.xml

<?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="com.xiejiaohui.domain.Student"/></typeAliases>
<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://localhost:3306/test"/>
            <property name="username" value="root"/>
            <property name="password" value="123456abcd"/>
        </dataSource>
    </environment>
</environments>
<mappers>
    <mapper resource="com/xiejiaohui/mappers/StudentMapper.xml"/>
</mappers>
</configuration>

需要引入的包 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion> 
  <groupId>com.xiejiaohui.study_mybatis</groupId>
  <artifactId>study_mybatis</artifactId>
  <version>1.0</version>
  <name>Study MyBatis</name>


<dependencies>
<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>org.slf4j</groupId>        <artifactId>slf4j-api</artifactId>        <version>1.7.5</version>    </dependency>
   <dependency>        <groupId>org.slf4j</groupId>        <artifactId>slf4j-log4j12</artifactId>        <version>1.7.5</version>        <scope>runtime</scope>    </dependency>
   <dependency>        <groupId>log4j</groupId>        <artifactId>log4j</artifactId>        <version>1.2.17</version>        <scope>runtime</scope>    </dependency>
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId>        <version>4.11</version>        <scope>test</scope>     </dependency>
</dependencies>

数据库建表语句

create table students(stud_id int(11) not null auto_increment, name varch
            ar(50) not null, email varchar(50) not null, dob date default null, primary key
            (stud_id));
原文地址:https://www.cnblogs.com/xiejh/p/5154982.html