1.建议使用STS工具自带插件建立Spring Starter Project工程,操作截图步骤如下:
到上面即可Finish完成项目创建,完整项目接口图如下:
2.编写application.yml配置文件:
# 数据库连接信息
spring:
datasource:
# 连接地址
url: jdbc:mysql://localhost:3306/fxc_test
# 数据库账号
username: root
# 数据库密码
password: root123
# 数据库驱动
driver-class-name: com.mysql.jdbc.Driver
# Spring Data JPA相关配置
jpa:
# 制定数据库类型
database: mysql
# 控制台打印SQL
show-sql: true
# 建表策略update,根据实体更新表结构
hibernate:
ddl-auto: update
naming:
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
3.实现AuditorAware接口:
这里Demo我们是定义的一个类似常量的userName,在正式项目中需要从用户权限模块中获取到当前登录的用户信息
package com.example.demo.config;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;
/**
* Spring Data JPA通过AuditorAware<T>接口获取用户信息,
* 其中泛型T可以为String保存用户名,也可以为Long/Integer保存用户ID
* @author lenovo
*
*/
@Component
public class UserNameAuditorAware implements AuditorAware<String> {
@Value("testName")
private String userName;
@Override
public Optional<String> getCurrentAuditor() {
return Optional.of(userName);
}
}
4.新建BaseModel,里面主要包含审计的公共字段,如新增人、新增时间、最后更新人、最后更新时间:
package com.example.demo.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import lombok.Data;
/**
* @Data:注解在类上;提供类所有属性的getting和setting方法,此外还提供了equals、canEqual、hashCode、toString方法
* @EntityListeners(AuditingEntityListener.class):声明实体监听器,用于实体修改时做处理
* @MappedSuperclass:声明该类为实体父类,不会映射单独的表,而是把字段映射到子类表中
*
* @author lenovo
*
*/
@Data
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
public class BaseModel {
/**
* 主键ID,根据数据库策越选择生成ID方式
*/
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
/**
* 表示该字段为创建人,在这个实体被insert的时候,会自动为其赋值
*/
@CreatedBy
@Column(name = "create_by")
private String createBy;
/**
* 表示该字段为创建时间字段,在这个实体被insert的时候,会自动为其赋值
*/
@CreatedDate
@Column(name = "create_time")
private Date createTime;
/**
* 表示该字段为修改人,在这个实体被update的时候,会自动为其赋值
*/
@LastModifiedBy
@Column(name = "last_update_by")
private String lastUpdateBy;
/**
* 表示该字段为修改时间字段,在这个实体被update的时候,会自动为其赋值
*/
@LastModifiedDate
@Column(name = "last_update_time")
private Date lastUpdateTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getLastUpdateBy() {
return lastUpdateBy;
}
public void setLastUpdateBy(String lastUpdateBy) {
this.lastUpdateBy = lastUpdateBy;
}
public Date getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(Date lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
@Override
public String toString() {
return "BaseModel [id=" + id + ", createBy=" + createBy + ", createTime=" + createTime + ", lastUpdateBy="
+ lastUpdateBy + ", lastUpdateTime=" + lastUpdateTime + "]";
}
}
5.添加t_person表entity,继承BaseModel
package com.example.demo.entity;
import javax.persistence.Entity;
import javax.persistence.Table;
import lombok.Data;
/**
* -数据库t_person表对应entity实体类
*
* @author fangxc
* @data 2018年7月25日 下午2:05:28
* @version 1.0.0
*
*/
@Data
@Entity
@Table(name = "t_person")
public class Person extends BaseModel {
private String name;
private String sex;
private Integer age;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Person [name=" + name + ", sex=" + sex + ", age=" + age + ", address=" + address + "]";
}
}
6.使用JPA针对Person实体创建对应的Repository接口实现,达到对该实体的数据访问
package com.example.demo.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.entity.Person;
/**
* 针对Person实体创建对应的Repository接口实现
* @author lenovo
*
*/
@Repository
public interface PersonRepository extends JpaRepository<Person, Long>{
}
7.启动类上面注解:@EnableJpaAuditing
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
/**
* SpringBoot项目启动类
*
* @author lenovo
*
*/
@EnableJpaAuditing
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
8.至此,前期准备工作完成,接下来在测试类中进行测试
CREATE TABLE `t_person` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`sex` varchar(255) DEFAULT NULL,
`age` int(3) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
`create_by` varchar(255) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`last_update_by` varchar(255) DEFAULT NULL,
`last_update_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
package com.example.demo;
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 com.example.demo.dao.PersonRepository;
import com.example.demo.entity.Person;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Autowired
private PersonRepository personRepository;
@Test
public void personAddTest() {
Person p = new Person();
p.setName("fxc");
p.setSex("man");
p.setAge(25);
p.setAddress("testAddress");
personRepository.save(p);
}
@Test
public void personUpdateTest() {
Person p = personRepository.findById(1L).get();
p.setAge(100);
personRepository.save(p);
}
}
运行personAddTest方法,数据库中数据为:
可以看到我们测试类中并没有set创建人和创建时间,但是数据中自动为我们生成了。
再运行personUpdateTest方法,数据库中数据为:
可以看到最后更新人和最后更新时间字段也自动更新了,到此说明我们DEMO成功!