Spring Boot高级教程之Spring Boot连接MySql数据库
spring boot可以大大简化持久化任务,几乎不需要写sql语句,在之前章节“spring boot 构建框架”中我们新建了一个spring boot应用程序,本章在原有的工程中与数据库建立连接。
spring boot有两种方法与数据库建立连接,一种是使用jdbctemplate,另一种集成mybatis,下面分别为大家介绍一下如何集成和使用这两种方式。
1. 使用jdbctemplate
<dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-jdbc</artifactid> </dependency>
在resource文件夹下添加application.properties配置文件并输入数据库参数,内容如下:
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.driver spring.datasource.max-idle=10 spring.datasource.max-wait=1000 spring.datasource.min-idle=5 spring.datasource.initial-size=5 server.port=8012 server.session.timeout=10 server.tomcat.uri-encoding=utf-8
新建controller类测试数据库连接,实例如下:
package com.example.demo; import java.util.iterator; import java.util.list; import java.util.map; import java.util.map.entry; import java.util.set; import org.springframework.beans.factory.annotation.autowired; import org.springframework.jdbc.core.jdbctemplate; import org.springframework.web.bind.annotation.pathvariable; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.restcontroller; @restcontroller @requestmapping("/mydb") public class dbcontroller { @autowired private jdbctemplate jdbctemplate; @requestmapping("/getusers") public list<map<string, object>> getdbtype(){ string sql = "select * from appuser"; list<map<string, object>> list = jdbctemplate.queryforlist(sql); for (map<string, object> map : list) { set<entry<string, object>> entries = map.entryset( ); if(entries != null) { iterator<entry<string, object>> iterator = entries.iterator( ); while(iterator.hasnext( )) { entry<string, object> entry =(entry<string, object>) iterator.next( ); object key = entry.getkey( ); object value = entry.getvalue(); system.out.println(key+":"+value); } } } return list; } @requestmapping("/user/{id}") public map<string,object> getuser(@pathvariable string id){ map<string,object> map = null; list<map<string, object>> list = getdbtype(); for (map<string, object> dbmap : list) { set<string> set = dbmap.keyset(); for (string key : set) { if(key.equals("id")){ if(dbmap.get(key).equals(id)){ map = dbmap; } } } } if(map==null) map = list.get(0); return map; } }
运行app输入地址输出数据库数据。
2. 集成mybatis
添加mybatis依赖,在pom.xml文件中增加如下:
<dependency> <groupid>org.mybatis.spring.boot</groupid> <artifactid>mybatis-spring-boot-starter</artifactid> <version>1.0.0</version> </dependency>
在resource文件夹下添加application.properties配置文件并输入数据库参数,如下:
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.driver spring.datasource.max-idle=10 spring.datasource.max-wait=1000 spring.datasource.min-idle=5 spring.datasource.initial-size=5 server.port=8012 server.session.timeout=10 server.tomcat.uri-encoding=utf-8
依次添加mapper的接口类和xml文件,类分别如下:
appmessagemapper.java
package com.example.demo.mapper; import java.util.list; import com.example.demo.bean.appmessage; public interface appmessagemapper { int deletebyprimarykey(string id); int insert(appmessage record); int insertselective(appmessage record); appmessage selectbyprimarykey(string id); int updatebyprimarykeyselective(appmessage record); int updatebyprimarykey(appmessage record); list<appmessage> selectall(); list<appmessage> getmessbyid(string id); }
appmessagemapper.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.example.demo.mapper.appmessagemapper" > <resultmap id="baseresultmap" type="com.example.demo.bean.appmessage" > <id column="id" property="id" jdbctype="varchar" /> <result column="message" property="message" jdbctype="varchar" /> <result column="senddate" property="senddate" jdbctype="timestamp" /> </resultmap> <sql id="base_column_list" > id, message, senddate </sql> <select id="selectbyprimarykey" resultmap="baseresultmap" parametertype="java.lang.string" > select <include refid="base_column_list" /> from appuser_message where id = #{id,jdbctype=varchar} </select> <delete id="deletebyprimarykey" parametertype="java.lang.string" > delete from appuser_message where id = #{id,jdbctype=varchar} </delete> <insert id="insert" parametertype="com.example.demo.bean.appmessage" > insert into appuser_message (id, message, senddate ) values (#{id,jdbctype=varchar}, #{message,jdbctype=varchar}, #{senddate,jdbctype=timestamp} ) </insert> <insert id="insertselective" parametertype="com.example.demo.bean.appmessage" > insert into appuser_message <trim prefix="(" suffix=")" suffixoverrides="," > <if test="id != null" > id, </if> <if test="message != null" > message, </if> <if test="senddate != null" > senddate, </if> </trim> <trim prefix="values (" suffix=")" suffixoverrides="," > <if test="id != null" > #{id,jdbctype=varchar}, </if> <if test="message != null" > #{message,jdbctype=varchar}, </if> <if test="senddate != null" > #{senddate,jdbctype=timestamp}, </if> </trim> </insert> <update id="updatebyprimarykeyselective" parametertype="com.example.demo.bean.appmessage" > update appuser_message <set > <if test="message != null" > message = #{message,jdbctype=varchar}, </if> <if test="senddate != null" > senddate = #{senddate,jdbctype=timestamp}, </if> </set> where id = #{id,jdbctype=varchar} </update> <update id="updatebyprimarykey" parametertype="com.example.demo.bean.appmessage" > update appuser_message set message = #{message,jdbctype=varchar}, senddate = #{senddate,jdbctype=timestamp} where id = #{id,jdbctype=varchar} </update> <select id="selectall" resultmap="baseresultmap"> select id, message, senddate from appuser_message order by senddate asc </select> <select id="getmessbyid" resultmap="baseresultmap" parametertype="java.lang.string"> select id, message, senddate from appuser_message where id = #{id,jdbctype=varchar} order by senddate asc </select> </mapper>
appmessage.java
package com.example.demo.bean; import java.util.date; public class appmessage { private string id; private string message; private date senddate; public string getid() { return id; } public void setid(string id) { this.id = id == null ? null : id.trim(); } public string getmessage() { return message; } public void setmessage(string message) { this.message = message == null ? null : message.trim(); } public date getsenddate() { return senddate; } public void setsenddate(date senddate) { this.senddate = senddate; } }
appmessageservice.java
package com.example.demo.service; import java.util.arraylist; import java.util.list; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.service; import com.example.demo.bean.appmessage; import com.example.demo.mapper.appmessagemapper; @service public class appmessageservice { @autowired private appmessagemapper mapper; public list<appmessage> getmessage(){ list<appmessage> list = new arraylist<appmessage>(); list.add(mapper.selectbyprimarykey("xtt")); //list = mapper.selectall(); return list; } public list<appmessage> getallmessage(){ list<appmessage> list = new arraylist<appmessage>(); list = mapper.selectall(); return list; } public int addmessage(appmessage appmessage) { return mapper.insert(appmessage); } public list<appmessage> getmessagebyid(string id) { return mapper.getmessbyid(id); } public int delmessage(string id) { return mapper.deletebyprimarykey(id); } }
appmessagecontroller.java
package com.example.demo.controller; import java.util.list; import org.springframework.beans.factory.annotation.autowired; import org.springframework.web.bind.annotation.requestbody; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestmethod; import org.springframework.web.bind.annotation.requestparam; import org.springframework.web.bind.annotation.restcontroller; import com.example.demo.bean.appmessage; import com.example.demo.service.appmessageservice; @restcontroller @requestmapping("/appmessage") public class appmessagecontroller { @autowired private appmessageservice service; @requestmapping("/getthree") public list<appmessage> getthreeformessage(){ list<appmessage> list = service.getmessage(); return list; } @requestmapping("/getall") public list<appmessage> getallmessage(){ list<appmessage> list = service.getallmessage(); int num = list.size(); if(null!=list && num>3){ for (int i = 0; i < num-3; i++) { list.remove(0); } } return list; } @requestmapping("/getbyid") public list<appmessage> getmessagebyid(@requestparam("id") string id){ list<appmessage> list = service.getmessagebyid(id); int num = list.size(); if(null!=list && num>5){ for (int i = 0; i < num-5; i++) { list.remove(0); } } return list; } @requestmapping(value = "/add",method = requestmethod.post) // 或者采用@postmapping("/add")方法,更加节省代码的编写量 public int addmessage(@requestbody appmessage appmessage){ return service.addmessage(appmessage); } @requestmapping(value="/delmessagebyid",method=requestmethod.post) // 或者采用@postmapping("/delmessagebyid")方法,更加节省代码的编写量 public int delmessagebyid(@requestparam("id") string id){ return service.delmessage(id); } }
问题描述?
springboot扫描包提示找不到mapper的问题,异常信息:
consider defining a bean of type in your configuration
分析原因
spring boot项目的bean装配默认规则是根据application类所在的包位置从上往下扫描,“application类”是指spring boot项目入口类。如果application类所在的包为:com.yoodb.blog,则只会扫描com.yoodb.blog包及其所有子包,如果service或dao所在包不在com.yoodb.blog及其子包下,则不会被扫描。
解决方法
方式一:使用注解@componentscan(value=”com.yoodb.blog”),其中,com.yoodb.blog为包路径。
方式二:将启动类application放在上一级包中,注意的是application启动类必须要保证在包的根目录下。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: Kotlin实现静态方法
推荐阅读
-
Spring Boot高级教程之使用Redis实现session共享
-
Spring Boot高级教程之Spring Boot连接MySql数据库
-
Java Maven:spring boot + Mybatis连接MySQL,通用mapper的增删改查,映射实现多表查询
-
Spring boot 数据库连接断线重连问题
-
Spring boot 数据库连接断线重连问题
-
Spring Boot 与 Kotlin 使用JdbcTemplate连接MySQL数据库的方法
-
Spring Boot 配置MySQL数据库重连的操作方法
-
Spring Boot 与 Kotlin 使用JdbcTemplate连接MySQL数据库的方法
-
详解Spring Boot Mysql 版本驱动连接池方案选择
-
Spring Boot 配置MySQL数据库重连的操作方法