Spring Boot 之整合 Mybatis

前置: 先搭建好Spring Boot 项目

教程:https://blog.csdn.net/zihu6848/article/details/81167865

1:maven添加jdbc和mybatis包

<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.3.1</version>
</dependency>

 2:将application.properties改名为application.yml

3:application.yml添加如下配置

#配置数据源
spring:
  datasource:
     url: jdbc:mysql://140.143.226.151:3306/LeetCode?useUnicode=true&characterEncoding=utf8
     username: root
     password: root
     driver-class-name: com.mysql.jdbc.Driver

SpringBoot会自动加载application.yml相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中。

4: 指定mybatis映射文件的地址

#指定mybatis映射文件的地址
mybatis:
  mapper-locations: classpath:mapper/*.xml

5:resources文件夹下创建mapper文件夹

这里插入一下application.yml的配置详解:

#配置数据源
spring:
  datasource:
     url: jdbc:mysql://140.143.226.151:3306/LeetCode?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&allowMultiQueries=true&useSSL=true
     username: root
     password: root
     driver-class-name: com.mysql.jdbc.Driver

#指定mybatis映射文件的地址
mybatis:
  mapper-locations: classpath:mapper/*.xml

 注意点:

1,原有的key,例如spring.jpa.properties.hibernate.dialect,按“.”分割,都变成树状的配置

2,key后面的冒号,后面一定要跟一个空格

3,把原有的application.properties删掉。然后一定要执行一下  maven -X clean install

6: 写一个测试方法访问数据库

 如上是我添加的文件,

GarageMapper.xml中写的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="garageMapper">

    <select id="getGarageList" resultType="java.util.Map">
      select * from garage
    </select>

</mapper>

GarageServiceImpl实现类:

package com.yk.service.impl;

import com.yk.dao.DAO;
import com.yk.service.GarageService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service("garageService")
public class GarageServiceImpl implements GarageService {

    @Resource(name = "daoSupport")
    private DAO dao;

    @Override
    public List<Map> getGarageList() throws Exception {
        return (List<Map>) dao.findForList("garageMapper.getGarageList",null);
    }
}

 

GarageService接口:
package com.yk.service;

import java.util.List;
import java.util.Map;

public interface GarageService {

    public List<Map> getGarageList() throws Exception;
}

 dao层,数据库访问封装方法:

package com.yk.dao;
/**
 * @author @author YK
 * 修改时间:2015、12、11
 */
public interface DAO {
	
	/**
	 * 保存对象
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object save(String str, Object obj) throws Exception;
	
	/**
	 * 修改对象
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object update(String str, Object obj) throws Exception;
	
	/**
	 * 删除对象 
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object delete(String str, Object obj) throws Exception;

	/**
	 * 查找对象
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object findForObject(String str, Object obj) throws Exception;

	/**
	 * 查找对象
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object findForList(String str, Object obj) throws Exception;
	
	/**
	 * 查找对象封装成Map
	 * @param s
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object findForMap(String sql, Object obj, String key, String value) throws Exception;
	
}

 

DaoSupport:
package com.yk.dao;

import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;
/**
 * @author @author YK
 * 修改时间:2015、12、11
 */
@Repository("daoSupport")
public class DaoSupport implements DAO {

	@Resource(name = "sqlSessionTemplate")
	private SqlSessionTemplate sqlSessionTemplate;
	
	/**
	 * 保存对象
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object save(String str, Object obj) throws Exception {
		return sqlSessionTemplate.insert(str, obj);
	}
	
	/**
	 * 批量更新
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object batchSave(String str, List objs )throws Exception{
		return sqlSessionTemplate.insert(str, objs);
	}
	
	/**
	 * 修改对象
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object update(String str, Object obj) throws Exception {
		return sqlSessionTemplate.update(str, obj);
	}

	/**
	 * 批量更新
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public void batchUpdate(String str, List objs )throws Exception{
		SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
		//批量执行器
		SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
		try{
			if(objs!=null){
				for(int i=0,size=objs.size();i<size;i++){
					sqlSession.update(str, objs.get(i));
				}
				sqlSession.flushStatements();
				sqlSession.commit();
				sqlSession.clearCache();
			}
		}finally{
			sqlSession.close();
		}
	}
	
	/**
	 * 批量更新
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object batchDelete(String str, List objs )throws Exception{
		return sqlSessionTemplate.delete(str, objs);
	}
	
	/**
	 * 删除对象 
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object delete(String str, Object obj) throws Exception {
		return sqlSessionTemplate.delete(str, obj);
	}
	 
	/**
	 * 查找对象
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object findForObject(String str, Object obj) throws Exception {
		return sqlSessionTemplate.selectOne(str, obj);
	}

	/**
	 * 查找对象
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object findForList(String str, Object obj) throws Exception {
		return sqlSessionTemplate.selectList(str, obj);
	}
	
	public Object findForMap(String str, Object obj, String key, String value) throws Exception {
		return sqlSessionTemplate.selectMap(str, obj, key);
	}
	
}


 

HelloWorld:
package com.yk.controller;

import com.yk.service.GarageService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class HelloWorld {

    @Resource(name = "garageService")
    GarageService garageService;

    @PostMapping(value = "/helloWorld", consumes = "application/json")
    public List<Map> helloWorld(){
        List<Map> garageList = new ArrayList();
        try {
            garageList = garageService.getGarageList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return garageList;
    }

}

 7:

接下来运行DemoApplication,用postman访问接口,查看数据库能否成功返回.

结果我测试接口的时候报了如下错误:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet successfully received from the server was 2,828 milliseconds ago.  The last packet sent successfully to the server was 2,812 milliseconds ago.
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_131]
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_131]
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_131]
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_131]
	at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.46.jar:5.1.46] .....................等

 网上查询了之后说是数据库连接超时

随后尝试了如下方法:

在JDBC URL上添加?autoReconnect=true,如下:

url: jdbc:mysql://140.143.226.151:3306/LeetCode?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&allowMultiQueries=true&useSSL=true&autoReconnect=true
随后又报错:
 Could not create connection to database server. Attempted reconnect 3 times. Giving up.

 思考:数据库账号密码都是对的,且昨天玩python的时候都能连没问题的,可能是我配置文件有什么地方没有配置好

之后发现,果然是配置错误,将jdbcUrl后面的&useSSL=true去掉即可

运行项目之后下面的错误可以无视,如果不想看到这个警告,就在jdbcURL后面的后面加上:&useSSL=false

Tue Jul 24 17:22:47 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

随后数据库访问成功,这东西居然搞了我一天,亏死了.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值