JAVA - SpringBoot项目引用MyBatis操作数据库
1. 创建SpringBoot项目,参考:https://www.cnblogs.com/1285026182YUAN/p/12329727.html
2. 引用generator生成 Mybatis文件,参考:https://www.cnblogs.com/1285026182YUAN/p/12334401.html
添加POM依赖:
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.19</version> </dependency>
创建Service相关文件,controller相关文件。
接口文件:orderservice
package com.example.recordboot.service; import com.example.recordboot.entity.TblOrder; import java.util.List; public interface OrderService { public TblOrder GetModel(); }
服务文件:orderserviceImpl
package com.example.recordboot.service; import com.example.recordboot.dao.TblOrderMapper; import com.example.recordboot.entity.TblOrder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class OrderServiceImpl implements OrderService { @Resource private TblOrderMapper tblOrderMapper; @Override public TblOrder GetModel() { TblOrder res = tblOrderMapper.selectByPrimaryKey(50); return res; } }
controller文件:
package com.example.recordboot.controller; import com.example.recordboot.entity.TblOrder; import com.example.recordboot.service.OrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/Order") public class OrderController { @Autowired private OrderService orderService; @RequestMapping("/GetModel") public TblOrder GetModel() { TblOrder res = orderService.GetModel(); return res; } }
RestController是responsebody+Controller两个注解的合体,一般就拿来直接传json数据。 为什么可以直接传个对象过去呢?这是因为springboot内置了jackson模块,可以在maven的依赖下看到这方面的jar包
简单的配置与设置:
好现在讲讲设置,这里会想到,那些Controller啊,@Service啊还有MyBatis的注解@Mapper什么的spring怎么知道在哪呢?不用像mvc那样搞个扫描设置吗?
是的要的,这些我们在启动类做了简单的设置:
package com.example.recordboot; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan(basePackages = "com.example.recordboot.dao")//这个注解注意一下 放DAO层的包名 对这个包下进行注入 public class RecordbootApplication { public static void main(String[] args) { SpringApplication.run(RecordbootApplication.class, args); } }
application.properties 配置文件
#设置端口号 server.port=8095 spring.devtools.restart.enabled=true spring.devtools.restart.additional-paths=src/main/java spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=123456 #mybatis配置 #首先是实体类所在的包的名字 mybatis.type-aliases-package=com.example.recordboot.entity mybatis.mapper-locations=classpath:mapper/*.xml #mybatis使用resources的xml来映射数据库表,这里就是resources下的mapper包的所有xml文件
dao 文件
package com.example.recordboot.dao; import com.example.recordboot.entity.TblOrder; public interface TblOrderMapper { int deleteByPrimaryKey(Integer id); int insert(TblOrder record); int insertSelective(TblOrder record); TblOrder selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(TblOrder record); int updateByPrimaryKey(TblOrder record); }
entity 文件
package com.example.recordboot.entity; import java.util.Date; public class TblOrder { private Integer id; private String orderCode; private Integer userId; private Integer amount; private Date uptime; private String text; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getOrderCode() { return orderCode; } public void setOrderCode(String orderCode) { this.orderCode = orderCode; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getAmount() { return amount; } public void setAmount(Integer amount) { this.amount = amount; } public Date getUptime() { return uptime; } public void setUptime(Date uptime) { this.uptime = uptime; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
mapper文件
<?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.recordboot.dao.TblOrderMapper" > <resultMap id="BaseResultMap" type="com.example.recordboot.entity.TblOrder" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="order_code" property="orderCode" jdbcType="VARCHAR" /> <result column="user_id" property="userId" jdbcType="INTEGER" /> <result column="amount" property="amount" jdbcType="INTEGER" /> <result column="uptime" property="uptime" jdbcType="TIMESTAMP" /> <result column="text" property="text" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List" > id, order_code, user_id, amount, uptime, text </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from tbl_order where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from tbl_order where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.example.recordboot.entity.TblOrder" > <selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER" > SELECT LAST_INSERT_ID() </selectKey> insert into tbl_order (order_code, user_id, amount, uptime, text) values (#{orderCode,jdbcType=VARCHAR}, #{userId,jdbcType=INTEGER}, #{amount,jdbcType=INTEGER}, #{uptime,jdbcType=TIMESTAMP}, #{text,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.example.recordboot.entity.TblOrder" > <selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER" > SELECT LAST_INSERT_ID() </selectKey> insert into tbl_order <trim prefix="(" suffix=")" suffixOverrides="," > <if test="orderCode != null" > order_code, </if> <if test="userId != null" > user_id, </if> <if test="amount != null" > amount, </if> <if test="uptime != null" > uptime, </if> <if test="text != null" > text, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="orderCode != null" > #{orderCode,jdbcType=VARCHAR}, </if> <if test="userId != null" > #{userId,jdbcType=INTEGER}, </if> <if test="amount != null" > #{amount,jdbcType=INTEGER}, </if> <if test="uptime != null" > #{uptime,jdbcType=TIMESTAMP}, </if> <if test="text != null" > #{text,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.example.recordboot.entity.TblOrder" > update tbl_order <set > <if test="orderCode != null" > order_code = #{orderCode,jdbcType=VARCHAR}, </if> <if test="userId != null" > user_id = #{userId,jdbcType=INTEGER}, </if> <if test="amount != null" > amount = #{amount,jdbcType=INTEGER}, </if> <if test="uptime != null" > uptime = #{uptime,jdbcType=TIMESTAMP}, </if> <if test="text != null" > text = #{text,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.example.recordboot.entity.TblOrder" > update tbl_order set order_code = #{orderCode,jdbcType=VARCHAR}, user_id = #{userId,jdbcType=INTEGER}, amount = #{amount,jdbcType=INTEGER}, uptime = #{uptime,jdbcType=TIMESTAMP}, text = #{text,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update> </mapper>
generatorConfig.xml 文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!--<properties resource="application.properties"/>--> <!--这里注释掉,后面集成插件的时候,在pom.xml文件导入驱动--> <!--<classPathEntry location="~/mysql/mysql-connector-java-8.0.19.jar" />--> <!--1,MyBatis3:默认的值; 2,MyBatis3Simple:生成的mapper和xml比较简洁干净--> <context id="Mysql" targetRuntime="MyBatis3" defaultModelType="flat"> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> <property name="javaFileEncoding" value="UTF-8"/> <!--pressAllComments:MyBatis3默认为false,true则默认不生成注释 suppressDate:MyBatis3默认为false,默认不生成时间戳--> <commentGenerator> <property name="suppressDate" value="true"/> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--新版mysql驱动用的是com.mysql.cj.jdbc.Driver,老版本的是com.mysql.jdbc.Driver--> <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC" userId="root" password="123456"> </jdbcConnection> <javaModelGenerator targetPackage="com.example.recordboot.entity" targetProject="src/main/java"/> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/> <javaClientGenerator targetPackage="com.example.recordboot.dao" targetProject="src/main/java" type="XMLMAPPER"/> <!--去掉example代码--> <table tableName="tbl_order" domainObjectName="TblOrder" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> <!--% 表示全部表--> <!--mysql 配置--> <generatedKey column="id" sqlStatement="Mysql" identity="true"/> <!--oracle 配置--> <!-- <generatedKey column="id" sqlStatement="select SEQ_{1}.nextval from dual" identity="false" type="pre"/> --> </table> </context> </generatorConfiguration>
完成。