Spring boot 用mybatis连接数据库

来源:互联网 发布:正品潮牌代购淘宝店 编辑:程序博客网 时间:2024/05/22 11:51

环境准备

建立Spring boot应用需要安装STS,不安装直接新建maven项目会报各种问题,反正我没有成功。eclipse安装STS在help菜单中点击”Eclipse Marketplace“,然后切换到popular选项,然后选择STS,install

创建Spring boot应用

安装STS后,右键新建Spring starter Project,type 选择Maven,填写名称等,最后点finish

pom.xml文件内容如下

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.shux</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>springboot</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.0.BUILD-SNAPSHOT</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter --><dependency>    <groupId>org.mybatis.spring.boot</groupId>    <artifactId>mybatis-spring-boot-starter</artifactId>    <version>1.3.0</version></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><configuration><skip>true</skip></configuration></plugin></plugins></build><repositories><repository><id>spring-snapshots</id><name>Spring Snapshots</name><url>https://repo.spring.io/snapshot</url><snapshots><enabled>true</enabled></snapshots></repository><repository><id>spring-milestones</id><name>Spring Milestones</name><url>https://repo.spring.io/milestone</url><snapshots><enabled>false</enabled></snapshots></repository></repositories><pluginRepositories><pluginRepository><id>spring-snapshots</id><name>Spring Snapshots</name><url>https://repo.spring.io/snapshot</url><snapshots><enabled>true</enabled></snapshots></pluginRepository><pluginRepository><id>spring-milestones</id><name>Spring Milestones</name><url>https://repo.spring.io/milestone</url><snapshots><enabled>false</enabled></snapshots></pluginRepository></pluginRepositories></project>

在resources下新建application.properties文件,文件内容如下

#数据库连接地址spring.datasource.url=jdbc:mysql://10.202.15.39:3306/rps #数据库用户名和密码spring.datasource.username=rpsspring.datasource.password=rps654321#数据库驱动spring.datasource.driver-class-name=com.mysql.jdbc.Driver#服务器端口,默认是8080server.port=8080

创建SpringbootApplication.java类,此类为Spring boot的启动类

@SpringBootApplication@ComponentScan(basePackages = {"com.shux"})//扫描Spring注解的包@MapperScan("com.shux.mapper")//扫描mybaits的mapper注解 这个很重要,如果不配置这个会报找不到bean错误public class SpringbootApplication {public static void main(String[] args) {SpringApplication.run(SpringbootApplication.class, args);}}
定义两个实体

package com.shux.entity;import java.io.Serializable;public class TnStudent implements Serializable {/** *  */private static final long serialVersionUID = 4265173931263772442L;private Integer id;private String name;private Integer age;public TnStudent(String name, Integer age) {super();this.name = name;this.age = age;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}}
package com.shux.entity;import java.io.Serializable;public class TnTeacher implements Serializable {/** *  */private static final long serialVersionUID = 7338482884226735533L;private Integer id;private String teaName;private Integer teaAge;public TnTeacher(String teaName, Integer teaAge) {super();this.teaName = teaName;this.teaAge = teaAge;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getTeaName() {return teaName;}public void setTeaName(String teaName) {this.teaName = teaName;}public Integer getTeaAge() {return teaAge;}public void setTeaAge(Integer teaAge) {this.teaAge = teaAge;}}

定义Mapper,注意:如果Mapper不在主类SpringbootApplication同一个包下,必须在主类SpringbootApplication中用@MapperScan定义这个Mapper的包

package com.shux.mapper;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Mapper;import org.apache.ibatis.annotations.Select;import com.shux.entity.TnStudent;@Mapperpublic interface ITnStudentMapper {@Insert("insert into tn_student(name,age) values (#{name},#{age})")void saveTnStudent(TnStudent tnStudent);@Select("select * from tn_student where id = #{id}")TnStudent loadTnStudentById(Integer id);}
package com.shux.mapper;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Mapper;import com.shux.entity.TnTeacher;@Mapperpublic interface ITnTeacherMapper {@Insert("insert into tn_teacher(tea_name,tea_age) values (#{teaName},#{teaAge})")void saveTnTeacher(TnTeacher tnTeacher);}

定义Biz接口及实现

package com.shux.biz;import com.shux.entity.TnStudent;public interface ITnStudentBiz {/** * 插入数据 * @param tnStudent * @throws Exception */void saveTnStudent(TnStudent tnStudent) throws Exception;/** * 查询数据 * @param id * @return */TnStudent loadTnStudentById(Integer id);}
package com.shux.biz;import com.shux.entity.TnTeacher;public interface ITnTeacherBiz {void saveTnTeacher(TnTeacher tnTeacher) throws Exception;}

package com.shux.biz.impl;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;import com.shux.biz.ITnStudentBiz;import com.shux.biz.ITnTeacherBiz;import com.shux.entity.TnStudent;import com.shux.entity.TnTeacher;import com.shux.mapper.ITnStudentMapper;@Service("tnStudentBiz")public class TnStudentBizImpl implements ITnStudentBiz {private @Autowired ITnStudentMapper studentMapper;private @Autowired ITnTeacherBiz tnTeacherBiz;@Override@Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRED)public void saveTnStudent(TnStudent tnStudent) throws Exception{studentMapper.saveTnStudent(tnStudent);TnTeacher tnTeacher = new TnTeacher("华晨曦",2);//try {tnTeacherBiz.saveTnTeacher(tnTeacher);//throw new Exception("错误!");//} catch (Exception e) {//e.printStackTrace();//}}@Overridepublic TnStudent loadTnStudentById(Integer id) {// TODO Auto-generated method stubreturn studentMapper.loadTnStudentById(id);}}
package com.shux.biz.impl;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;import com.shux.biz.ITnTeacherBiz;import com.shux.entity.TnTeacher;import com.shux.mapper.ITnTeacherMapper;@Service("tnTeacherBiz")public class TnTeacherBizImpl implements ITnTeacherBiz {private @Autowired ITnTeacherMapper teacherMapper;@Override@Transactional(rollbackFor=Exception.class,propagation = Propagation.REQUIRED)public void saveTnTeacher(TnTeacher tnTeacher) throws Exception{teacherMapper.saveTnTeacher(tnTeacher);//throw new Exception("错误!");}}

定义Control类

package com.shux.springboot;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.shux.biz.ITnStudentBiz;import com.shux.entity.TnStudent;@RestController@RequestMapping("/student")public class StudentController {private @Autowired ITnStudentBiz tnStudentBiz;@RequestMapping("/saveStudent")public String saveStudent(){String result = "";TnStudent tnStudent = new TnStudent("simba",30);try {tnStudentBiz.saveTnStudent(tnStudent);result = "插入成功";} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();result = "插入失败";}return result;}@RequestMapping("/loadStudent")public String loadStudent(Integer id){TnStudent student = tnStudentBiz.loadTnStudentById(id);return  "name:" + student.getName() +" age:"+ student.getAge();}}

启动SpringbootApplication类,然后在浏览其中输入http://localhost:8080/student/saveStudent,然后显示插入成功并且在数据库中查询到tn_student和tn_teacher中的数据了。


然后在浏览器中输入http://localhost:8080/student/loadStudent.do?id=2即可查询到之前插入的数据。

然后就完美的搭建成功了~