1.springboot集成jdbcTemplate模板
引入相应的mysql和jdbcTemplate包
<!-- jdbcTemplat jdb模板依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- mysql 依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
配置相关application.yml相关数据源配置
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
username: root
password: 123456
配置相关application.properties
#mysql jdbc数据源
spring.datasource.url=jdbc:mysql://localhost:3306/test1?verifyServerCertificate=false&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
编写案列
@Service
public class UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
public String addUser(String name,Integer age){
jdbcTemplate.update("INSERT INTO `test`.`t_user` (`name`, `age`) VALUES (?, ?);",name,age);
return "SUCCESS";
}
}
## 2.springboot集成JPA 引入相应的JPA包
<!-- jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
创建entity实体类
@Entity(name = "t_user")
public class UserEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "age")
private Integer age;
get set...
JPA常用的注解
(https://www.jianshu.com/p/38d247f02724)
创建接口继承JPA JpaRepository
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
@Component
public interface UserDao extends JpaRepository<UserEntity,Integer> {
}
调用相对应的controlle
@RequestMapping(value = "/getUser")
@ResponseBody
public String getUser(Integer id){
UserEntity userEntity = userDao.findById(id).get();
return userEntity.toString();
}
扫描jpa的dao层和实体类可以写和不写 @EnableJpaRepositories("com.dao") @EntityScan("com.entity")
3.springboot集成Mybatis
引入jar包
<!-- mysql 依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Spring Boot Mybatis 依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
遇坑说明一下:mybatis1.2.0 jar,包存在问题,导致mapper扫描不进去,网上一大堆解决办法都有尝试都没有用,后面换了一个版本就可以了版本不兼容
1.配置mybatis文件内容
yml
mybatis:
mapperLocations: classpath*:mapper/*.xml #mapper文件地址
#config-location: classpath:mybatis-config.xml
typeDaoPackage: com.huangan.mapper #dao层
typeAliasesPackage: com.huangan.entity #实体类
properties
#配置.xml文件路径
#mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:/com/mapper/*.xml
#配置模型路径
mybatis.type-aliases-package=com.entity
2.创建dao层
import com.huangan.entity.UserEntity;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.jboss.logging.Param;
import org.springframework.stereotype.Component;
@Component
public interface UserMapper {
//@Select("select id,name,age from t_user where id =#{id}")
//public UserEntity selectByUserId(@Param(value = "id") Integer id);
public UserEntity getUser(@Param("name") String name);
}
3.mapper.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.dao.UserMapper">
<select id="getUser" parameterType="string" resultType="com.entity.UserEntity">
select * from t_user
where name = #{name}
</select>
</mapper>
说明一下:注册mapper 有两种:1.就是在每个dao里使用@Mapper注解,2.在springboot启动写入@MapperScan注解。
3.创建Mapper文件
4.springboot集成mybatis plus+lombok整合
引入jar包
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
</parent>
<dependencies>
<!-- druid 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!-- mybatisPlus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
<!-- mybatis plus 代码生成器依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.1.0</version>
</dependency>
<!-- 代码生成器模板 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<!-- lombok简化java代码 如果没有安装,先安装这个插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- mysql 依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
配置mybatisPlus值创建applcation-mybatis.yml
#数据源
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
#使用druid连接池
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC
username: root
password: 123456
#mybatisPlus配置
mybatis-plus:
global-config:
db-config:
id-type: auto
field-strategy: not_empty
table-underline: true
db-type: mysql
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
mapper-locations: classpath:/mapper/*.xml
创建MyBatisPlusConfig.class 文件
/**
* mybatisPlus配置
*/
@Configuration
public class MyBatisPlusConfig {
/**
* @description: 配置分页插件
* @author: gradual
* @param: []
* @return: com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
/**
* @description: SQL执行效率插件
* @author: gradual
* @param: []
* @return: com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor
*/
@Bean
@Profile({"test"})// 设置 dev test 环境开启
public PerformanceInterceptor performanceInterceptor() {
return new PerformanceInterceptor();
}
/**
* 逻辑删除用,3.1.1之后的版本可不需要配置该bean,但项目这里用的是3.1.0的
* @author David Hong
* @return com.baomidou.mybatisplus.core.injector.ISqlInjector
*/
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
}
创建mybatsPlus代码生成器 MysqlGenerator.class
/**
* 代码生成器
*/
public class MysqlGenerator {
/**
* RUN THIS
*/
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
// TODO 设置用户名
gc.setAuthor("huangan");
gc.setOpen(true);
// service 命名方式
gc.setServiceName("%sService");
// service impl 命名方式
gc.setServiceImplName("%sServiceImpl");
// 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setFileOverride(true);
gc.setActiveRecord(true);
// XML 二级缓存
gc.setEnableCache(false);
// XML ResultMap
gc.setBaseResultMap(true);
// XML columList
gc.setBaseColumnList(false);
mpg.setGlobalConfig(gc);
// TODO 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// TODO 包配置
PackageConfig pc = new PackageConfig();
//pc.setModuleName(scanner("模块名"));
pc.setParent("com.huangan");
pc.setEntity("entity");
pc.setService("service");
pc.setServiceImpl("service.impl");
mpg.setPackageInfo(pc);
// 自定义需要填充的字段
List<TableFill> tableFillList = new ArrayList<TableFill>();
//如 每张表都有一个创建时间、修改时间
//而且这基本上就是通用的了,新增时,创建时间和修改时间同时修改
//修改时,修改时间会修改,
//虽然像Mysql数据库有自动更新几只,但像ORACLE的数据库就没有了,
//使用公共字段填充功能,就可以实现,自动按场景更新了。
//如下是配置
//TableFill createField = new TableFill("gmt_create", FieldFill.INSERT);
//TableFill modifiedField = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
//tableFillList.add(createField);
//tableFillList.add(modifiedField);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/src/main/resources/mapper/"
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.setTemplate(new TemplateConfig().setXml(null));
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
// 设置逻辑删除键
strategy.setLogicDeleteFieldName("deleted");
// TODO 指定生成的bean的数据库表名
strategy.setInclude("t_user");
//strategy.setSuperEntityColumns("id");
// 驼峰转连字符
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
// 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
点击运行MysqlGenerator运行main方法创建对应的实体类,mapper,service,dao