今天我们就来继续探讨一下springboot的数据持久层方面的内容,springboot整合jpa,如图
<!-- jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
这里要注意一下mysql-connector6.0以上的配置
spring.datasource.url=jdbc:mysql://localhost:3380/user?useSSL=false&useUnicode=true&characterEncoding=utf-8&useAffectedRows=true&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
jpa方面的配置
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
然后直奔主题,来看看实体类User
package yick.demo.springboot;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user")
public class User {
@Column(name = "name")
private String name;
@Column(name = "age")
private Integer age;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private String id;
public User() {
}
public User(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
JPA接口类UserRepository
package yick.demo.springboot;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, String> {
}
Controller类
package yick.demo.springboot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
@RestController
@RequestMapping(value = "view")
public class ThymeleafController {
@Autowired
public UserRepository userRepository;
@GetMapping(value = "info/{id}")
public String info(@PathVariable String id) {
User user = userRepository.findById(id).get();
return JSON.toJSONString(user);
}
}
就这样我们做了最简单的演示,访问http://localhost:8080/view/info/123,可看如图

image.png
最后代码请留意我的码云。

有你的支持,我会更努力哦!!!.jpg