springboot具有非常棒的持久层框架支持,下面我将介绍我用过的三种持久层框架进行简述使用。
由于这里操作的都是一张表,这里贴出通用的yml和建表语句 切记这里使用的是mysql8 ,5.8之前的朋友请修改后缀去掉com.mysql.cj.jdbc.Driver 中的cj。
DROP TABLE IF EXISTS `Test`;
CREATE TABLE `Test` (`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',`age` int(11) NULL DEFAULT NULL COMMENT '年龄',`inhere` tinyint(4) NULL DEFAULT NULL COMMENT '在不在',PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;SET FOREIGN_KEY_CHECKS = 1;
spring:datasource:url: jdbc:mysql://192.168.8.100:3306/FuLinTest?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=trueusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driver
JdbcTemplate
首先呢看下项目结构
记得使用之前千万不要不加依赖哈哈
<!-- jdbcTemplate --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>
然后贴出实体类
package com.maoxs.pojo;import lombok.Data;import java.io.Serializable;@Data
public class MyTest implements Serializable {private Long id;private String name;private int age;private Boolean inhere;public MyTest() {}public MyTest(String name, int age, Boolean inhere) {this.name = name;this.age = age;this.inhere = inhere;}public MyTest(Long id, String name, int age, Boolean inhere) {this.id = id;this.name = name;this.age = age;this.inhere = inhere;}@Overridepublic String toString() {final StringBuffer sb = new StringBuffer("MyTest{");sb.append("id=").append(id);sb.append(", name='").append(name).append('\'');sb.append(", age=").append(age);sb.append(", inhere=").append(inhere);sb.append('}');return sb.toString();}
}
然后是dao层的实现类和接口
package com.maoxs.dao;import com.maoxs.pojo.MyTest;public interface MyTestDao {MyTest selectOne(Long id);int insert(MyTest myTest);int delete(Long id);int update(MyTest myTest);
}
package com.maoxs.dao.impl;import com.maoxs.dao.MyTestDao;
import com.maoxs.pojo.MyTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;@Repository
public class MyTestDaoImpl implements MyTestDao {@Autowiredprivate JdbcTemplate jdbcTemplate;@Overridepublic MyTest selectOne(Long id) {String sql = "select id,name,age,inhere from Test where id=? ";return jdbcTemplate.queryForObject(sql, (resultSet, i) -> {MyTest myTest = new MyTest();myTest.setId(resultSet.getLong("id"));myTest.setName(resultSet.getString("name"));myTest.setAge(resultSet.getInt("age"));myTest.setInhere(resultSet.getBoolean("inhere"));return myTest;}, id);}@Overridepublic int insert(MyTest myTest) {String sql = "insert into Test (name,age,inhere) values(?,?,?)";return jdbcTemplate.update(sql, myTest.getName(), myTest.getAge(), myTest.getInhere());}@Overridepublic int delete(Long id) {String sql = "delete from Test where id=?";return jdbcTemplate.update(sql, id);}@Overridepublic int update(MyTest myTest) {String sql = "update Test set name=?,age=?,inhere=? where id=?";return jdbcTemplate.update(sql, myTest.getName(), myTest.getAge(), myTest.getInhere(), myTest.getId());}
}
然后呢编写测试看看都能用不
package com.maoxs;import com.maoxs.dao.MyTestDao;
import com.maoxs.pojo.MyTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.Collections;
import java.util.List;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootJdbcApplicationTests {@Autowiredprivate MyTestDao myTestDao;@Testpublic void insert() {MyTest myTest = new MyTest("fulin", 18, true);myTestDao.insert(myTest);}@Testpublic void selectOne() {System.out.println(myTestDao.selectOne(1L));}@Testpublic void update() {MyTest myTest = new MyTest(1L, "fulin", 18, true);myTestDao.update(myTest);}@Testpublic void delete() {myTestDao.delete(13L);}
}
ok 我这边测试都通过了
Spring Data jpa
首先呢还是先看下项目结构
然后使用的时候千万不要忘了加依赖
<!-- jpa --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency>
先看下实体,不要写错注解
package com.maoxs.pojo;import lombok.Data;import javax.persistence.*;
import java.io.Serializable;@Data
@Entity
@Table(name = "MyTest")
public class MyTest implements Serializable {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;@Columnprivate String name;@Columnprivate int age;@Columnprivate Boolean inhere;
}
SpringBoot创建DAO层很多种方法其中japrepository是最强大的而且最有特色的一种,我们可以针对不同的实体创建repository接口。Spring会根据方法名称的规则进行自动生成实现,强大的不要不要的。在SpringBoot中默认已经提供了非常多的常规CRUD操作的repository,以下就是Spring为我们提供的repository接口
package com.maoxs.dao;import com.maoxs.pojo.MyTest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;import java.util.List;@Repository
public interface TestDao extends JpaRepository<MyTest, Long> {
}
别看啥都没有功能超级牛逼 具体可以去jpa官网学习下怎么使用的 JPA 学习手册
在看下service
package com.maoxs.service;import com.maoxs.pojo.MyTest;import java.util.List;public interface TestService {void add(MyTest tset) throws Exception;void update(MyTest myTest) throws Exception;void del(Long id) throws Exception;List<MyTest> select() throws Exception;
}
package com.maoxs.service.impl;import com.maoxs.dao.TestDao;
import com.maoxs.pojo.MyTest;
import com.maoxs.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class TestServiceImpl implements TestService {@Autowiredprivate TestDao testDao;@Overridepublic void add(MyTest tset) throws Exception {testDao.save(tset);}@Overridepublic void update(MyTest myTest) throws Exception {testDao.saveAndFlush(myTest);}@Overridepublic void del(Long id) throws Exception{testDao.deleteById(id);}@Overridepublic List<MyTest> select() throws Exception {return testDao.findAll();}
}
然后写个测试类测试下
package com.maoxs;import com.maoxs.pojo.MyTest;
import com.maoxs.service.TestService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootJpaApplicationTests {@Autowiredprivate TestService testService;@Testpublic void add() throws Exception {MyTest t = new MyTest();t.setAge(11);t.setInhere(false);t.setName("DesrCat");testService.add(t);}@Testpublic void update() throws Exception {MyTest t = new MyTest();t.setAge(180);t.setInhere(false);t.setName("昴先生111");t.setId(1L);testService.update(t);}@Testpublic void select() throws Exception {List<MyTest> select = testService.select();Assert.assertTrue(select.size() > 0);System.out.println(Collections.unmodifiableCollection(select));}@Testpublic void del() throws Exception {testService.del(11L);}}
我这里是都通过了你呢?
Mybatis
这里看下项目结构
依赖依赖依赖依赖
<!--mybatis --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId></dependency>
这里的yml需要加入
mybatis:mapper-locations: classpath:/mapper/*.xmltype-aliases-package: com.maoxs.pojo
然后呢是实体
package com.maoxs.pojo;import lombok.Data;import java.io.Serializable;@Data
public class MyTest implements Serializable {private Long id;private String name;private int age;private Boolean inhere;}
然后呢是dao
package com.maoxs.dao;import com.maoxs.pojo.MyTest;
import org.springframework.stereotype.Repository;import java.util.List;@Repository
public interface MyTestMapper {List<MyTest> findAll();
}
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.maoxs.dao.MyTestMapper"><sql id="base_sql">a.id as id,a.name as name,a.age as age,a.inHere as inHere</sql><select id="findAll" resultType="com.maoxs.pojo.MyTest">select<include refid="base_sql"/>fromTest a</select>
</mapper>
切记在启动类上加入MapperScan 注解
package com.maoxs;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@MapperScan("com.maoxs")
public class SpringbootMybatisApplication {public static void main(String[] args) {SpringApplication.run(SpringbootMybatisApplication.class, args);}
}
然后是测试类
package com.maoxs;import com.maoxs.dao.MyTestMapper;
import com.maoxs.pojo.MyTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.Collections;
import java.util.List;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootMybatisApplicationTests {@Autowiredprivate MyTestMapper myTestMapper;@Testpublic void findAll() {List<MyTest> all = myTestMapper.findAll();System.out.println(Collections.unmodifiableCollection(all));}}
mybatis就不多说了,应该经常用吧实在不会的小伙伴 点击 mybatis 学习手册
然后呢就推荐大家使用mybatis的一个开源插件myabtis-plus
//TODO 后期呢我会放上使用帖子
mybatis-plus 学习手册
本博文是基于springboot2.x 如果有什么不对的请在下方留言。