简单的MyBatis demo之数据库增删改查

来源:互联网 发布:佳能自带修图软件 编辑:程序博客网 时间:2024/05/12 12:24

参考mybatis官方文档:点击打开链接


mybatis简介(摘自官方文档):MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

构成:SqlSessionFactoryBuilder     ——>通过xm配置文件构建出SqlSessionFactory   ——>获取SqlSession

 1.sqlSessionFactoryBuilder

这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。因此 SqlSessionFactoryBuilder 实例的最佳范围是方法范围(也就是局部方法变量)。你可以重用 SqlSessionFactoryBuilder 来创建多个 SqlSessionFactory 实例,但是最好还是不要让其一直存在以保证所有的 XML 解析资源开放给更重要的事情。

2.SqlSessionFactory

SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由对它进行清除或重建。使用 SqlSessionFactory 的最佳实践是在应用运行期间不要重复创建多次,多次重建 SqlSessionFactory 被视为一种代码“坏味道(bad smell)”。因此 SqlSessionFactory 的最佳范围是应用范围。有很多方法可以做到,最简单的就是使用单例模式或者静态单例模式。

3.SqlSession

每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的范围是请求或方法范围。绝对不能将 SqlSession 实例的引用放在一个类的静态域,甚至一个类的实例变量也不行。也绝不能将 SqlSession 实例的引用放在任何类型的管理范围中,比如 Serlvet 架构中的 HttpSession。如果你现在正在使用一种 Web 框架,要考虑 SqlSession 放在一个和 HTTP 请求对象相似的范围中。换句话说,每次收到的 HTTP 请求,就可以打开一个 SqlSession,返回一个响应,就关闭它。这个关闭操作是很重要的,你应该把这个关闭操作放到 finally 块中以确保每次都能执行关闭。


准备工作: 1.该项目是基于maven的。

      2.数据库:mysql


 表:

CREATE TABLE `student` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `name` varchar(10) DEFAULT NULL,  `sex` varchar(10) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 |


目录结构



1.pom.xml,添加依赖包

<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.mybatis</groupId><artifactId>MybatisDemo</artifactId><packaging>war</packaging><version>0.0.1-SNAPSHOT</version><name>MybatisDemo Maven Webapp</name><url>http://maven.apache.org</url><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.1</version></dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.38</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>3.0.5.RELEASE</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.0</version></dependency></dependencies><build><finalName>MybatisDemo</finalName><defaultGoal>compile</defaultGoal></build></project>


2.mybatis-config.xml

XML 配置文件(configuration XML)中包含了对 MyBatis 系统的核心设置,包含获取数据库连接实例的数据源(DataSource)和决定事务范围和控制方式的事务管理器(TransactionManager)

<?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> <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/mybatisDemo?characterEncoding=GBK"/><property name="username" value="root"/><property name="password" value="root"/></dataSource></environment></environments> <mappers><mapper resource="com/entity/StudentMapper.xml"/></mappers></configuration>

3. StudentMapper.xml 映射表

3.1 typeAliases

类型别名是为 Java 类型设置一个短的名字。它只和 XML 配置有关,存在的意义仅在于用来减少类完全限定名的冗余

如:

<typeAlias alias="Student" type="com.example.student.Student"/>

3.2 resultMap和resultType,不能同时使用。

resultType:结果的类型。可以使用 JavaBeans 或 POJOs来作为映射对象。

resultMap:结果集。可以解决列名不匹配,定义你sql想返回的结果集。

<?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.example.dao.StudentDao"><resultMap type="com.example.student.Student" id="studentList"><id property="id" column="id" javaType="java.lang.Integer"/><result property="name" column="name" javaType="java.lang.String"/><result property="sex" column="sex" javaType="java.lang.String"/></resultMap><select id="queryOneStudent" parameterType="int" resultType="com.example.student.Student"><--! 这就是全名(包含包路径),如果设置了别名就可以只用别名 -->select * from student where id=#{id}</select><insert id="addStudent">insert into student (name,sex) values(#{name},#{sex})</insert><delete id="deleteOneStudent" parameterType="int">delete from student where id=#{id}</delete><update id="updateOneStudent" >update student set name=#{student.name},student.sex=#{student.sex} where id=#{id}</update><select id="queryAllStudent"  resultMap="studentList">select * from student</select></mapper>


4.MybatisUtil类,将sessionFactory的初始化提成util类避免重复代码。

public class MybatisUtil {public static SqlSessionFactory initSqlSessionFactory() {String resource = "mybatis/mybatis-config.xml";InputStream inputStream = null;SqlSessionFactoryBuilder sessionFactoryBuilder = null;SqlSessionFactory sessionFactory = null;try {inputStream = Resources.getResourceAsStream(resource);sessionFactoryBuilder = new SqlSessionFactoryBuilder();sessionFactory = sessionFactoryBuilder.build(inputStream);} catch (Exception e) {e.printStackTrace();}return sessionFactory;}public static SqlSession initSqlSession() {SqlSession session = initSqlSessionFactory().openSession();return session;}public static void closeOrCommitSession(SqlSession session,int flag) {if (flag == 0) {session.close();} else {session.commit();session.close();}}}

5.StudentDao

Notice:如果不用@Param注解,会报异常:

Cause: org.apache.ibatis.binding.BindingException: Parameter 'id' not found. Available parameters are [0, student, param1, param2]

public interface StudentDao {public Student queryOneStudent(int id);public void addStudent(Student student);public void deleteOneStudent(int id);public void updateOneStudent(@Param("id") int id, @Param("student") Student student);public List<Student> queryAllStudent();}


6.StudentDaoImpl

Notice:记得每次关闭session。另外,insert,update,delete操作还要用commit方法。这里为了代码可读性,提成了个common util方法。

public class StudentDaoImpl implements StudentDao {private static final int ONLY_CLOSE_FLAG = 0;private static final int COMMIT_CLOSE_FLAG = 1;public Student queryOneStudent(int id) {SqlSession session = MybatisUtil.initSqlSession();StudentDao studentDao = session.getMapper(StudentDao.class);Student student = studentDao.queryOneStudent(id);System.out.println("queryOneStudent-->>" + id);MybatisUtil.closeOrCommitSession(session, ONLY_CLOSE_FLAG);return student;}public void addStudent(Student student) {SqlSession session = MybatisUtil.initSqlSession();StudentDao studentDao = session.getMapper(StudentDao.class);studentDao.addStudent(student);System.out.println("addStudent-->>" + student.getName());MybatisUtil.closeOrCommitSession(session, COMMIT_CLOSE_FLAG);}public void deleteOneStudent(int id) {SqlSession session = MybatisUtil.initSqlSession();StudentDao studentDao = session.getMapper(StudentDao.class);studentDao.deleteOneStudent(id);System.out.println("deleteOneStudent-->>" + id);MybatisUtil.closeOrCommitSession(session, COMMIT_CLOSE_FLAG);}public void updateOneStudent(int id, Student student) {SqlSession session = MybatisUtil.initSqlSession();StudentDao studentDao = session.getMapper(StudentDao.class);studentDao.updateOneStudent(id, student);System.out.println("updateOneStudent-->>" + id + student.getName());MybatisUtil.closeOrCommitSession(session, COMMIT_CLOSE_FLAG);}public List<Student> queryAllStudent() {SqlSession session = MybatisUtil.initSqlSession();StudentDao studentDao = session.getMapper(StudentDao.class);List<Student> studentList = studentDao.queryAllStudent();System.out.println("queryAllStudent-->>" );MybatisUtil.closeOrCommitSession(session, ONLY_CLOSE_FLAG);return studentList;}}


7.Student 实体类
public class Student {private int id;private String name;private String sex;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}@Overridepublic String toString() {return "Student [id=" + id + ", name=" + name + ", sex=" + sex + "]";}}


8.Test类,也是将要测试功能的提出了一些方法。

public class Test {public static void main(String[] args) {StudentDao studentDao = new StudentDaoImpl();//StudentService studentService = new StudentServiceImpl();queryAllStudent(studentDao);//addStudent(studentDao);//deleteOneStudent(studentDao);//updateOneStudent(studentDao);}public static void queryOneStudent(StudentDao studentDao) {Student student = studentDao.queryOneStudent(3);System.out.println(student.toString());}public static void addStudent(StudentDao studentDao) {Student student = new Student();student.setName("huang2");student.setSex("female");studentDao.addStudent(student);}public static void deleteOneStudent(StudentDao studentDao) {studentDao.deleteOneStudent(4);}public static void updateOneStudent(StudentDao studentDao) {Student student = new Student();student.setName("wu1");student.setSex("male");studentDao.updateOneStudent(5, student);}public static void queryAllStudent(StudentDao studentDao) {List<Student> students = studentDao.queryAllStudent();for (Student student : students) {System.out.println(student.toString());}}}



0 0