demo源代码 https://github.com/wzjwhut/springboot-hibernate-jpa
官方教程 https://docs.spring.io/spring-data/jpa/docs/2.1.5.RELEASE/reference/html/
配置spring boot属性
官方文档
https://docs.spring.io/spring-boot/docs/2.1.3.RELEASE/reference/htmlsingle/#howto-configure-jpa-properties
https://docs.spring.io/spring-boot/docs/2.1.3.RELEASE/reference/htmlsingle/#boot-features-connect-to-production-database
server.port=8080
server.servlet.context-path=/
spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
production-database
spring.datasource.url=jdbc:mysql://localhost:3306/database1
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
编写Entity
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
@Entity
@Table
@Data //用于自动生成getter和setter, idea需要安装插件
public class Person {
@Id
private long id;
private String emailAddress; //column名称映射规则: java使用驼峰格式, 数据库使用下划线格式, emailAddress将映射为email_address
private String lastname;
private String firstname;
}
编写Repository
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* https://docs.spring.io/spring-data/data-commons/docs/current/reference/html/
*/
@Repository
public interface PersonRepository extends CrudRepository<Person, Long> {
/** 像写sql语句一样, 写方法名. 如果参数太多, 写起来也挺累的 */
List<Person> findByEmailAddressAndLastname(String emailAddress, String lastname);
// Enables the distinct flag for the query
List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);
List<Person> findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname);
// Enabling ignoring case for an individual property
List<Person> findByLastnameIgnoreCase(String lastname);
// Enabling ignoring case for all suitable properties
List<Person> findByLastnameAndFirstnameAllIgnoreCase(String lastname, String firstname);
// Enabling static ORDER BY for a query
List<Person> findByLastnameOrderByFirstnameAsc(String lastname);
List<Person> findByLastnameOrderByFirstnameDesc(String lastname);
List<Person> findByIdGreaterThan(long id);
//分页
Page<Person> queryFirst10ByLastname(String lastname, Pageable pageable);
//使用hql语句
@Query("SELECT a FROM Person a WHERE a.id=:id")
Person findByIdWithQuery(@Param("id") long id);
//修改
@Modifying
@Transactional
@Query("update Person a set a.firstname=:firstname WHERE a.id=:id")
int updateWithQuery(@Param("id") long id, @Param("firstname") String firstname);
}