SpringBoot与JPA
SpringBoot与JPA
Demo
项目结构
项目源码
package com.supremepole.b03springbootjpa;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class B03SpringBootJpaApplication {
public static void main(String[] args) {
SpringApplication.run(B03SpringBootJpaApplication.class, args);
}
}
package com.supremepole.b03springbootjpa;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* @author CodeCoderCoding
*/
public interface WebsiteDao extends JpaRepository<Website, Integer> {
/**
* 查找具有最大id的网站
* 注:nativeQuery=true表示
* @return
*/
@Query(value = "select * from website where id=(select max(id) from website)",nativeQuery = true)
Website getMaxIdWebsite();
/**
* 通过名字查找网站
* 注:@Query中的变量必须与@Param中的变量同名
* @param name
* @return
*/
@Query(value="select w from website w where w.name=:websiteName")
Website getWebsiteByName(@Param("websiteName") String name);
/**
* 查找符合w.id大于等于方法参数id值的所有网站实体
* 注:问号后的数字(1和2)代表变量在方法中的位置
* @param id
* @param name
* @return
*/
@Query(value="select w from website w where w.id>=?1 and w.name=?2")
List<Website> getWebsiteListById(int id, String name);
}
package com.supremepole.b03springbootjpa;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* @author CodeCoderCoding
*/
@Entity(name="website")
public class Website {
@Id
private int id;
private String url;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString(){
return "id="+id+" ,name"+name+" ,url"+url;
}
}
server.port=8081
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/spring-demo?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&allowPublicKeyRetrieval=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.show-sql=true
spring.jpa.database=mysql
spring.jpa.hibernate.ddl-auto=update