SpringBoot⾼级教程之SpringBoot连接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.sql.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
新建Controller类测试数据库连接,实例如下:
ample.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.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 = Set( );
if(entries != null) {
Iterator<Entry<String, Object>> iterator = entries.iterator( );
while(iterator.hasNext( )) {
mysql高级教程视频
Entry<String, Object> entry =(Entry<String, Object>) ( );
Object key = Key( );
Object value = Value();
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")){
(key).equals(id)){
map = dbmap;
}
}
}
}
if(map==null)
map = (0);
return map;
}
}
运⾏App输⼊地址输出数据库数据。
2. 集成Mybatis
添加mybatis依赖,在l⽂件中增加如下:
<dependency>
<groupId&batis.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.sql.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
依次添加mapper的接⼝类和xml⽂件,类分别如下:
AppMessageMapper.java
ample.demo.mapper;
import java.util.List;
ample.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);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/mybatis-3-mapper.dtd" > <mapper namespace="ample.demo.mapper.AppMessageMapper" >
<resultMap id="BaseResultMap" type="ample.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="ample.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="ample.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="ample.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="ample.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
ample.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) {
}
public Date getSenddate() {
return senddate;
}
public void setSenddate(Date senddate) {
this.senddate = senddate;
}
}
AppMessageService.java
ample.demo.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
ample.demo.bean.AppMessage;
ample.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) {
MessById(id);
}
public int delMessage(String id) {
return mapper.deleteByPrimaryKey(id);
}
}
APPMessageController.java
ller;
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;
ample.demo.bean.AppMessage;
ample.demo.service.AppMessageService;
@RestController
@RequestMapping("/appmessage")
public class APPMessageController {
@Autowired
private AppMessageService service;
@RequestMapping("/getThree")
public List<AppMessage> getThreeForMessage(){
List<AppMessage> list = Message();
return list;
}
@RequestMapping("/getAll")
public List<AppMessage> getAllMessage(){
List<AppMessage> list = AllMessage();
int num = list.size();
if(null!=list && num>3){
for (int i = 0; i < num-3; i++) {
}
}
return list;
}
@RequestMapping("/getByID")
public List<AppMessage> getMessageById(@RequestParam("id") String id){
List<AppMessage> list = MessageById(id);
int num = list.size();
if(null!=list && num>5){
for (int i = 0; i < num-5; i++) {
}
}
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类所在的包为:db.blog,则只会扫描db.blog包及其所有⼦包,如果service或dao所在包不在db.blog及其⼦包下,则不会被扫描。
解决⽅法
⽅式⼀:使⽤注解@ComponentScan(value=”db.blog”),其中,db.blog为包路径。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。