SpringBoot_持久化方案_JPA
额外需要数据连接池配置提供DataSource对象
依赖pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
配置文件bootstrap.yml
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
配置源码
@SpringBootApplication
@EntityScan("com.plxc.domain")//扫描实体类
public class Main {
public static void main(String[] args) throws Exception {
SpringApplication.run(Main.class, args);
}
}
//DAO层定义示例代码一
public interface JpaTbUserRepository extends JpaRepository<JpaTbUser, Integer>{
@Query(value = "select * from tb_user b where b.mobile=?1", nativeQuery = true)
List<JpaTbUser> findList(String username);
}
//示例代码二、执行原生SQL
public interface TransactionRepository extends JpaRepository<Transaction, Long> {
@Query(value ="select * from transaction where id>?1 limit ?2", nativeQuery = true)
List< Transaction > getTransactions(Integer startIndex, Integer limit);
}
//示例代码三、
//①构建PageRequest对象
Order nameOrder = new Order(Direction.DESC, "sname");
Order rangeOrder = new Order(Direction.ASC, "rangeMileage");
List<Order> orders = new ArrayList<Order>();
orders.add(nameOrder);//先按线路降序
orders.add(rangeOrder);//再按里程升序
Sort sort2 = new Sort(orders);
Pageable pageable = new PageRequest(pageNum, size, sort2);
//②分页查询
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1",
countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",nativeQuery = true)
Page<User> findByLastname(String lastname, Pageable pageable);
}
//示例代码三、使用自定义参数名
public interface UserRepository extends JpaRepository<User, Long> {
@Query("select u from User u where u.firstname = :firstname or u.lastname = :lastname")
User findByLastnameOrFirstname(@Param("lastname") String lastname, @Param("firstname") String firstname);
}
//示例代码四、约定抽象函数的命名
public interface ResourceRepository extends JpaRepository<Resource, Long> {
public List<Resource> findByUrl(String url);
}
/**
* 用户实体类
*
* @author vander
*
*/
@Data
@Entity
@Table(name="tb_user") //指定数据库表名
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"})
public class JpaTbUser implements Serializable{
private static final long serialVersionUID = 1L;
@Id
//@GeneratedValue( strategy = GenerationType.IDENTITY) //自增主键需配置
private long userId;
private String username;
private String mobile;
//@Column(name="pw") //变量并如果跟数据字段不一致需要注解指定
private String password;
private Date createTime;
}