SpringBoot 整合JPA,数据快速持久化。
整体采用:Hibernate,MySQL
pom.xml:
<!-- Spring-data-jpa基础包、MySQL驱动 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
#MySQl lian jie pei zhi wen jian
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
#JPA pei zhi xin xi
spring.jpa.database=MYSQL
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming-stratrgy=org.hibernate.cfg.ImproveNamingStrategy
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
Entity:
public class Demo{
//主键
@Id
//主键生成策略
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
private String password;
@JSONField(format="yyyy-MM-dd HH:mm")
private Date createTime;
//是否需要序列化
@JSONField(serialize=false)
private String remark;
//一堆get/set;各种Constructors
}
Service:
@Service
public class DemoServie{
@Resource
private DemoRepository demoRepository;
@Transactional
public void save(Demo demo){
demoRepository.save(demo);
}
@Transactional
public void delete(int id){
demoRepository.delete(id);
}
public Iterable<Demo> getAll(){
return demoRepository.findAll();
}
}
Repository:
public interface DemoRepository extends CrudRepository<Demo,Integer>{
}
@RestController
public class HellowController{
@Autowired
private DemoSerivce demoService;
@RequestMapping("/save")
public String save(){
Demo demo=new Demo();
demo.setName("test");
demo.setPasswoed("test");
demo.setCreateTime(new Date());
demo.setRemark("remark");
demoService.save(demo);
return "Y";
}
@RequestMapping("/delete")
public String delete(){
//无此id会报错,这里先不处理了
demoService.delete(1);
return "Y";
}
@RequestMapping("/getAll")
public Iterable<Demo> getAll(){
return demoService.getAll();
}
}