pom依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
application.yml配置文件
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/dev
username: dev
password: dev
hikari:
maximum-pool-size: 15
minimum-idle: 5
connection-timeout: 30000 # default 30s, ms
pool-name: SimpleHikariCP # change hikari pool name,default HikariPool-1
jpa:
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
show-sql: true
hibernate:
ddl-auto: update
server:
port: 8081
user:
id: 2
配置用户信息 AuditorAware T是泛型,可以自定义
/**
* @author whh
* @date 2019/3/21 9:05
*/
@Component
public class User implements AuditorAware<Long> {
@Value("${user.id:1}")
private Long userId;
@Override
public Optional<Long> getCurrentAuditor() {
return Optional.of(userId);
}
}
配置基类
/**
* @author whh
* @date 2019/3/21 9:09
*/
@Data
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
public class BaseModel {
/**
* 主键ID,根据数据库策越选择生成ID方式
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* 表示该字段为创建人,在这个实体被insert的时候,会自动为其赋值
*/
@CreatedBy
@Column(name = "create_by",nullable = false)
private Long createBy;
/**
* 表示该字段为创建时间字段,在这个实体被insert的时候,会自动为其赋值
*/
@CreatedDate
@Column(name = "create_time", nullable = false)
private Date createTime;
/**
* 表示该字段为修改人,在这个实体被update的时候,会自动为其赋值
*/
@LastModifiedBy
@Column(name = "last_update_by", nullable = false)
private Long lastUpdateBy;
/**
* 表示该字段为修改时间字段,在这个实体被update的时候,会自动为其赋值
*/
@LastModifiedDate
@Column(name = "last_update_time", nullable = false)
private Date lastUpdateTime;
}
配置实体类
**
* @author whh
* @date 2019/3/21 9:10
*/
@Table(name = "person")
@Entity
@Data
@org.hibernate.annotations.Table(appliesTo = "person", comment = "人员表")
public class Person extends BaseModel {
private String name;
private String sex;
private Integer age;
}
这里@DATA注解是lombok包的注解,需要引用lombak插件 会自动生成get方法set方法
启动类配置
@EnableJpaAuditing
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
repository
/**
* @author whh
* @date 2019/3/21 9:13
*/
@Repository
public interface PersonRepository extends JpaRepository<Person, Long> {
}
测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Autowired
private PersonRepository personRepository;
@Test
public void contextLoads() {
Person person = new Person();
person.setAge(19);
person.setName("whh");
person.setSex("男");
personRepository.save(person);
}
}