你知道SpringBoot整合JPA要怎样才能够实现吗?下面要给大家分享的就是SpringBoot整合jpa实例方面的内容,一起来了解一下。
SpringBoot整合JPA实例
导入maven依赖jar包:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
在application.properties配置JPA属性:
spring.jpa.database = mysql## 指定数据库 spring.jpa.show - sql = true## 是否显示执行sql语句 spring.jpa.hibernate.ddl - auto = update## 自动更新数据库表 若需要创建表则改为create
创建实体类User和Part,定义两个类用于关联查询,查询出用户的同时获取所在的部门信息:
import lombok.Data; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; @Entity @Table(name = "user") @Data public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "name") private String name; @Column(name = "job") private String job; @Column(name = "pid") private Integer pid; public User(String name, String job, Integer pid) { this.name = name; this.job = job; this.pid = pid; } public User() {} }
import lombok.Data; import javax.persistence.*; @Entity @Table(name = "part") @Data public class Part { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer pid; @Column(name = "partname") private String partname; }
创建接口UserRepository集成JpaRespository:
import com.irootech.bean.User; import com.irootech.dao.Impl.UserPortDao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Component; import java.util.List; @Component public interface UserRepository extends JpaRepository < User, Integer > { //添加用户 User save(User user); //条件查询 List < User > findByName(String name); //关联查询 @Query可以用于自定义sql语句,如果是修改需加上@Modifying ,这是一条关联查询语句,返回的结果映射到新对象中,新对象为接口,里面含有对应参数的构造方法。 @Query(value = "select u.id,u.name,u.job,u.pid,p.partname from user u left join part p on u.pid=p.pid ", nativeQuery = true) public List < UserPortDao > findViewInfo(); }
UserPortDao接口编写:
public interface UserPortDao { int getId(); String getName(); int getPid(); String getJob(); String getPartname(); }
测试类:
@Test public void contextLoads() { User user = new User("zhangsanlisi", "前端", 1); // repository.save(user); String str = "zhangsanlisi"; // List<User> users=repository.findByName(str); // System.out.println(users); List < UserPortDao > viewInfos = userInfoRepository.findViewInfo(); for (UserPortDao viewInfo: viewInfos) { System.out.println(viewInfo.getId() + viewInfo.getJob() + viewInfo.getName() + viewInfo.getPid() + viewInfo.getPartname()); } }
更多相关内容,请继续关注奇Q工具网的常见问题栏目来进行了解吧。
推荐阅读: