MyBatis与SpringBoot

来源:互联网 发布:手机giftbox是什么软件 编辑:程序博客网 时间:2024/06/16 01:02

Mybatis

1、什么是MyBatis?

   MyBatis是支持普通SQL查询、存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置,以及对结果的检索。MyBatis可以使用简单的xml或注解用于配置和原始映射,将接口和Java的POJO(plain oldjava objects,普通的Java对象)映射成数据库中的记录。

 

2、原理

   每一个MyBatis的应用程序都以一个SqlSessionFactory对象的实例为核心。SqlSessionFactory对象的实例可以通过SqlSessionFactoryBuilder对象来获得。SqlSessionFactoryBuilder对象可以通过xml配置文件,或者从Configuration类实例中来构建SqlSessionFactory对象。

3、MyBatis和SpringBoot结合

分三步,将MyBatis导入我的SpringBoot工程中:

(1)在application.porperties增加spring配置数据库URL

spring.datasource.url=jdbc:mysql://localhost:3306/fastnews?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
mybatis.config-location=classpath:mybatis-config.xml
#logging.level.root=DEBUG
spring.velocity.suffix=.html
spring.velocity.cache=false
spring.velocity.toolbox-config-location=toolbox.xml

 

(2)porm.xml增加依赖

<dependency>   <groupId>mysql</groupId>   <artifactId>mysql-connector-java</artifactId>   <scope>runtime</scope></dependency><dependency>   <groupId>org.mybatis.spring.boot</groupId>   <artifactId>mybatis-spring-boot-starter</artifactId>   <version>1.1.1</version></dependency>

(3)在templates包下添加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>    <settings>        <!-- Globally enables or disables any caches configured in any mapper under this configuration -->        <setting name="cacheEnabled" value="true"/>        <!-- Sets the number of seconds the driver will wait for a response from the database -->        <setting name="defaultStatementTimeout" value="3000"/>        <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->        <setting name="mapUnderscoreToCamelCase" value="true"/>        <!-- Allows JDBC support for generated keys. A compatible driver is required.        This setting forces generated keys to be used if set to true,         as some drivers deny compatibility but still work -->        <setting name="useGeneratedKeys" value="true"/>    </settings>    <!-- Continue going here --></configuration>

 

4、测试

(1)将sql文件拷贝至test/resources目录下。

(2)在model包下建立与数据库字段对应的User类和News类。

(3)在DAO包下新建一个UserDAO类:

package com.LilyDianer.FastNews.dao;import com.LilyDianer.FastNews.model.User;import org.apache.ibatis.annotations.*;/** * Created by Administrator on 2017/7/27. */@Mapperpublic interface UserDAO {    String TABLE_NAME = "user";    String INSET_FIELDS = " name, password, salt, head_url ";    String SELECT_FIELDS = " id, name, password, salt, head_url";    @Insert({"insert into ", TABLE_NAME, "(", INSET_FIELDS,            ") values (#{name},#{password},#{salt},#{headUrl})"})    int addUser(User user);    @Select({"select ", SELECT_FIELDS, " from ", TABLE_NAME, " where id=#{id}"})    User selectById(int id);    @Update({"update ", TABLE_NAME, " set password=#{password} where id=#{id}"})    void updatePassword(User user);    @Delete({"delete from ", TABLE_NAME, " where id=#{id}"})    void deleteById(int id);}

(4)编写测试用例

在test包下新建一个InitDatabaseTests类

package com.LilyDianer.FastNews;import com.LilyDianer.FastNews.dao.NewsDAO;import com.LilyDianer.FastNews.dao.UserDAO;import com.LilyDianer.FastNews.model.News;import com.LilyDianer.FastNews.model.User;import org.junit.Assert;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.SpringApplicationConfiguration;import org.springframework.test.context.jdbc.Sql;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import org.springframework.test.context.web.WebAppConfiguration;import java.util.Date;import java.util.Random;/** * Created by Administrator on 2017/7/27. */@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = FastNewsApplication.class)@Sql("/init-schema.sql")public class InitDatabaseTests {    @Autowired    UserDAO userDAO;    @Autowired    NewsDAO newsDAO;    @Test    public void initData() {        Random random = new Random();        for (int i = 0; i < 11; ++i) {            User user = new User();            user.setName(String.format("USER%d", i));            user.setPassword("");            user.setSalt("");            userDAO.addUser(user);            News news = new News();            news.setCommentCount(i);            Date date = new Date();            date.setTime(date.getTime() + 1000*3600*5*i);            news.setCreatedDate(date);            news.setLikeCount(i+1);            news.setUserId(i+1);            news.setTitle(String.format("TITLE{%d}", i));                    newsDAO.addNews(news);            user.setPassword("newpassword");            userDAO.updatePassword(user);        }        Assert.assertEquals("newpassword", userDAO.selectById(1).getPassword());        userDAO.deleteById(1);        Assert.assertNull(userDAO.selectById(1));    }}

5、查错

第一次运行的时候报错:

java.lang.IllegalStateException: Failed toload ApplicationContext

Caused by:org.springframework.beans.factory.UnsatisfiedDependencyException: Errorcreating bean with name 'newsDAO' defined in file [D:\study_resource_JAVA \FastNews\FastNews\target\classes\com\LilyDianer\FastNews\dao\NewsDAO.class]:Unsatisfied dependency expressed through bean property 'sqlSessionFactory':Error creating bean with name 'sqlSessionFactory' defined in class pathresource[org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Beaninstantiation via factory method failed; nested exception isorg.springframework.beans.BeanInstantiationException: Failed to instantiate[org.apache.ibatis.session.SqlSessionFactory]: Factory method'sqlSessionFactory' threw exception; nested exception isjava.io.FileNotFoundException: class path resource [mybatis-config.xml] cannotbe opened because it does not exist; nested exception isorg.springframework.beans.factory.BeanCreationException: Error creating beanwith name 'sqlSessionFactory' defined in class path resource[org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Beaninstantiation via factory method failed; nested exception isorg.springframework.beans.BeanInstantiationException: Failed to instantiate[org.apache.ibatis.session.SqlSessionFactory]: Factory method'sqlSessionFactory' threw exception; nested exception isjava.io.FileNotFoundException: class path resource [mybatis-config.xml] cannotbe opened because it does not exist

     

第一问题说的是我的 mybatis-config.xml 找不到,我开始把它放到了templements下,是错的。应该直接放到和properties一个目录下。JUnit4测试时配置文件的路径不能错。参考【http://blog.csdn.net/mjl960108/article/details/52916015】。

第二问题是class path resource [init-schema.sql]cannot be opened because it does not exist 这个文件,我是新建了一个resource包,放进去的,这个包的位置应该与Java包的位置同等,而不是Java包下的。而且注解部分也应该是@Sql("/init-schema.sql"),不能够写全路径。

 

修改之后,运行成功:

2017-07-27 17:08:24.003  INFO 2208 --- [           main]o.s.jdbc.datasource.init.ScriptUtils    : Executing SQL script from class path resource [init-schema.sql]

2017-07-27 17:08:24.742  INFO 2208 --- [           main]o.s.jdbc.datasource.init.ScriptUtils    : Executed SQL script from class path resource [init-schema.sql] in 738ms.

2017-07-27 17:08:26.248  INFO 2208 --- [       Thread-1] s.c.a.AnnotationConfigApplicationContext: Closingorg.springframework.context.annotation.AnnotationConfigApplicationContext@7714e963:startup date [Thu Jul 27 17:08:20 CST 2017]; root of context hierarchy

 

Process finished with exit code 0

 

原创粉丝点击