myBatis学习笔记

    最近辞职在家,找工作不是很顺利,就顺便看看技术吧,对hibernate用的较多,mybatis用的少,但是最近似乎mybatis更流行一下,今天抽空看了一下,其实就是找官方的文档,大牛的博客看看,然后自己组装一下,然后做个笔记。

     mybatis是一个SQL map框架,简单来说,就是把SQL结果映射为Java对象,这点对于喜欢SQL,注意性能的朋友来说,比较喜欢,学习曲线平坦。Hibernate相对来说要难一些,几乎就相当于实现了一个数据库,对数据库的方方面面以及缓存、加载方面都做了封装,直接将表的行和Java做了对应,操作起来很方便,而且也提供了很多默认方法,而且Spring还提供了Respository模式的方法,操作简单的GUID非常方便,代码很少,就可以使用了。当然,如果复杂的操作,Hibernate用起来反而不方便,需要写HQL或者SQL,SQL代码还是分布在代码之中,失去了面向对象的便利以及代码的美感。可能基于这个原因,mybatis流行起来,程序员可以得到完全操纵的满足感,这点很重要。顺便说一句,工作流引擎JBPM和Activiti实际上是同源的,只是在JBpm4之后,产生了分歧,创始人认为开发人员的便利性最重要,但团队不同意,创始人只好另起炉灶,开发了Activiti,个人认为,程序员觉得不方便,但是性能很高或者说学术水平很高的东西,其实很难流行,除非有一个方便的封装。

     1、环境

          Windows 10

           JDK 1.8.101

           NetBeans 8.2

           STS 4.6

           Mysql 5.6,数据库名为study

     2、应用程序模式(main()执行)

         1)建表SQL          

1 CREATE TABLE `info_user` (
2     `id` INT(11) NOT NULL AUTO_INCREMENT,
3     `user_name` VARCHAR(50) NULL DEFAULT NULL,
4     `password` VARCHAR(50) NULL DEFAULT NULL,
5     `comment` VARCHAR(500) NULL DEFAULT NULL,
6     PRIMARY KEY (`id`),
7     UNIQUE INDEX `user_name` (`user_name`)
8 )
9 ;

         2)mybatis的配置文件和Hibernate差不多,都是一个主配置文件,关联着若干mapper文件,文件如下

           mybatis-config.xml  (位于目录com/shiyq/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>
  <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/study?characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="com/shiyq/mybatis/mapper/UserDaoMapper.xml"/>
  </mappers>
</configuration>

  UserDaoMapper.xml (位于目录com/shiyq/mybatis/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="com.shiyq.mybatis.config.UserDao">
    <select id="countAll" resultType="int">
        select count(*) c from info_user;
    </select>
    
    <select id="selectAll" resultType="com.shiyq.mybatis.config.User">
        select * from info_user order by user_name asc
    </select>
    
    <insert id="insert" parameterType="com.shiyq.mybatis.config.User">
        insert into info_user(user_name,password,comment) values(#{user_name},#{password},#{comment})
    </insert>
    
    <update id="update" parameterType="com.shiyq.mybatis.config.User">
        update info_user set user_name=#{user_name},password=#{password},comment=#{comment} where user_name=#{user_name}
    </update>
    
    <delete id="delete" parameterType="String">
        delete from info_user where user_name=#{user_name}
    </delete>
    
    <select id="findByUserName" parameterType="String" resultType="com.shiyq.mybatis.config.User">
        select * from info_user where user_name=#{user_name}
    </select>
</mapper>

 

  可以看出mybatis-config.xml记录了数据库连接方式,以及mapper文件的列表。

      mapper文件也非常简单,需要注意几个关键的地方:

  •       mapper标签的namespace指定的是这个mapper对应的java类
  •       select,update,insert,delete代表了操作类型,其下的id代表了java类的方法名称。parameterType代表了参数类型,resultType代表结果类型,类型可以是基本类型,如int,long,也可以是java类型如String,com.shiyq.batis.config.user  

      另外需要注意,在netbeans中,这两个配置文件要放在target/classes下面,因为默认情况下src下面的文件不会拷贝到classes下,所以会出现找不到配置文件的错误。

      3)Java代码

         

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.shiyq.mybatis.config;

/**
 *
 * @author shiyq
 */
public class User {
    
    private int id;
    private String user_name;
    private String password;
    private String comment;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUser_name() {
        return user_name;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }  
    
}

  

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.shiyq.mybatis.config;

import java.util.List;

/**
 *
 * @author shiyq
 */
public interface UserDao {
    
    public int insert(User user);
    public int update(User user);
    public int delete(String user_name);
    public List<User> selectAll();
    public int countAll();
    public User findByUserName(String user_name);
}

      可以看出User是作为返回类型,而UserDao是mapper文件对应的接口文件,可以看出其返回值、参数类型、方法名称是一致的。

      4)运行

           到此,基本的配置就完成了,我们可以进行增删改查了,我们写个测试类,看一下

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.shiyq.mybatis;

import com.shiyq.mybatis.config.User;
import com.shiyq.mybatis.config.UserDao;
import java.io.Reader;
import java.util.Iterator;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 *
 * @author shiyq
 */
public class MybatisMain {
    public static void main(String args[])throws Exception
    {
        String user_name = "shiyq"+String.valueOf(Math.random()*100000).substring(0,3);
        String resource = "com/shiyq/mybatis/mybatis-config.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(reader);
        
        try (SqlSession session = factory.openSession()) {
            UserDao userDao = session.getMapper(UserDao.class);
            
            User user = new User();
            user.setUser_name(user_name);
            user.setPassword("stone123");
            user.setComment("备注");
            
            userDao.insert(user);
            System.out.println("记录条数:"+userDao.countAll());
            
            List<User> users = userDao.selectAll();
            Iterator<User> iter = users.iterator();
            
            while(iter.hasNext()){
                User u = iter.next();
                System.out.println("用户名:"+u.getUser_name()+", 密码:"+u.getPassword());
            }
            
            user.setComment("comment");
            userDao.update(user);
            //User u = userDao.findByUserName(user_name);
            User u = session.selectOne("com.shiyq.mybatis.config.UserDao.findByUserName",user_name);
            System.out.println("comment is "+u.getComment());
            
            //userDao.delete(user_name);
            System.out.println("记录条数:"+userDao.countAll());
            session.commit();
        }
    }
}

     运行结果如下:

记录条数:1
用户名:shiyq509, 密码:stone123
comment is comment
记录条数:1

 3、SpringBoot集成mybatis

       SpringBoot是相对较新的Spring开发方式,大大减少了配置文件,在开发和部署上的便利性都有很大的提升。

       采用STS作为开发工具,File->New->Spring Starter Project,如下图

     后面是要预先导入的包,选择SQL下的Mysql、JDBC、MyBatis,然后确定,生成项目即可。

     如果已经有Spring Boot项目,可以在pom.xml增加如下内容

		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.1.1</version>
		</dependency>

  spring boot的配置文件是src/main/resources/application.properties,我的配置文件如下

server.port=8080
server.context-path=/study

#log
logging.file=park/log.log
logging.level.org.cqgy=DEBUG

#jdbc
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/study?characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456

spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
spring.datasource.validation-query=SELECT 1
spring.datasource.test-on-borrow=false
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=18800
spring.datasource.jdbc-interceptors=ConnectionState;SlowQueryReport(threshold=0)

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=false
spring.jackson.serialization.indent-output=true

server.error.whitelabel.enabled=true

mybatis.config-location=classpath:mybatis/mybatis-config.xml

  默认情况下,只需要配置黑体字的部分即可,需要注意的是在web程序的情况下,需要在路径上增加"classpath:",否则还会出现找不到配置文件的现象。

      Spring boot情况下,mybatis会使用默认的datasource,自动创建SqlSessionFactory,SqlSession,自动装载Mapper的Java类。

      这里还是使用上面的文件,只不过位置有变化,如下

mybatis-config.xml  src/main/resources/mybatis
UserDaoMapper.xml  src/main/resources/mybatis/mapper
User.java  src/main/java/com/shiyq/mybatis/domain
UserDao.java src/main/java/com/shiyq/mybatis/dao

     mybatis-config.xml中的映射部分修改如下

<mappers>
    <mapper resource="mybatis/mapper/UserDaoMapper.xml"/>
  </mappers>

  然后写一个Controller作为测试

package com.shiyq.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.shiyq.mybatis.dao.UserDao;
import com.shiyq.mybatis.domain.User;

@Controller
public class UserList {

	@Autowired
	UserDao userDao;

	@RequestMapping("/user/list")
	public String userList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter pt = response.getWriter();
		
		User user1 = new User();
		String user_name = "shiyq"+String.valueOf(Math.random()*100000).substring(0,3);
		user1.setUser_name(user_name);
		user1.setPassword("密码");
		user1.setComment("注释,"+user_name);
		userDao.insert(user1);
		List<User> users = userDao.selectAll();
		int i = 0;
		pt.println("<pre>");
		int count = this.userDao.countAll();

		pt.println(count);
		for (User user : users) {
			System.out.println("用户名:" + user.getUser_name() + ", 密码:" + user.getPassword());
			pt.print(++i+", ");
			pt.println("用户名:" + user.getUser_name() + ", 密码:" + user.getPassword()+", 注释:"+user.getComment());
		}
		pt.println("</pre>");
		return null;

	}
}

  运行http://localhost:8080/study/user/list,结果如下

1
1, 用户名:shiyq204, 密码:密码, 注释:注释,shiyq204

  

 

posted @ 2016-10-19 10:07  stone-fly  阅读(784)  评论(0编辑  收藏  举报