依赖树关系:
![14083857_SSuc.png](https://i-blog.csdnimg.cn/blog_migrate/9a3c82ddc12699c1446e6039c6712917.png)
新建一个数据库db_book:
CREATE TABLE `t_book` (`db_book`db_book``db_book`
`id` int(11) NOT NULL AUTO_INCREMENT,
`author` varchar(50) DEFAULT NULL,
`NAME` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
/*Data for the table `t_book` */
insert into `t_book`(`id`,`author`,`NAME`) values (1,'java编程思想','小二'),(2,'php编程','老王');
项目和数据库连接配置:
server:
port: 9090
context-path: /
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db_book
username: root
password: root
jpa:
hibernate:
ddl-auto: update
show-sql: true
其中server是用来配置端口和路径
spring.datasource用来配置数据源
spring.jpa用来配置jpa
spring.jpa.hibernate.ddl-auto:
参数:create:启动时删除上一次生成的表,并根据实体类生成表,表中数据会被清空
create-drop:启动时根据实体类生成表,sessionFactory关闭时表会被删除
update:启动时会根据实体类生成表,当实体类属性变动的时候,表结构也会更新,开发初期用这个。
none:不采取任何措施。
spring.jpa.show-sql:设置hibernate操作的时候在控制台显示真实的sql语句。
spring.jackson.serialization.index_output=true,让控制台输出json更美观。
定义实体类:
Book.java
package cn.javabb.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="t_book")
public class Book {
@Id
@GeneratedValue
private Integer id;
@Column(length=100)
private String name;
@Column(length=50)
private String author;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
@Entity注解指明这是一个和数据库表映射的实体类
@Id注解指明这个属性映射为数据库的主键
@Generated
value注解默认使用主键生成方式为自增,hibernate会为我们自动生成一个序列
@Column注解普通属性,不注解的时候hibernate会自动根据属性名生成数据表的字段名,如属性name,映射成字段NAME,多字母属性如testName会自动映射为TEST_NAME。
定义访问接口
package cn.javabb.dao;
import java.util.List;
import javax.persistence.Transient;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import cn.javabb.entity.Book;
public interface BookDao extends JpaRepository<Book, Integer>{
//= select * from t_book where name=':name'
public List<Book> findByName(String name);
//= select * from t_book where name like ':name' ,:name=%name%
public List<Book> findByNameLike(String name);
//= select * from t_book where name = :name and author=:author
public Book findByNameAndAuthor(String name,String author);
/**
* HQL 自定义查询,
* SQL查询 nativeQuery = true
* @param name
* @return
*/
@Query(value="select t from Book t where t.name = :name")
public Book queryWithName(@Param("name")String name);
@Modifying
@Transactional
@Query(value="update t_book set name=:name where id=:id",nativeQuery=true)
public int updateName(@Param("id")Integer id,@Param("name")String name);
}
继承JpaRepository就自动拥有查询数据库的实例方法。
注意:
@Query()查询,中可以定义一个自己的SQL,默认是HQL查询,通过nativeQuery=true可以定义为SQL查询
更新查询:JPA 支持
@Modifying和@Query(SQL)注解组合事件来更新查询
@Modifying
@Transactional
@Query(SQL)
测试实例类:
package cn.javabb;
import java.util.List;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import cn.javabb.dao.BookDao;
import cn.javabb.entity.Book;
@RunWith(SpringRunner.class)
@SpringBootTest
public class BootJpaApplicationTests {
@Resource
BookDao bookDao;
@Test
public void contextLoads() {
}
/**
* 查询全部
*/
@Test
public void findAll(){
List<Book> bList = bookDao.findAll();
System.out.println("findAll:"+bList.size());
}
@Test
public void findOne(){
Book b = bookDao.findOne(2);
System.out.println("book:"+b);
}
@Test
public void queryWithName(){
Book b = bookDao.queryWithName("小二");
System.out.println("book:"+b);
}
@Test
public void findByName(){
List<Book> bList = bookDao.findByName("老王");
System.out.println("findByName:"+bList.size());
}
/**
* 新增 , 不用设置主键
* 调用CrudRepository
*/
@Test
public void save(){
Book b = new Book("Spring入门","javabb");
Book newB=bookDao.save(b);
System.out.println("save:"+newB);
}
/**
* 更新 update , 用save方法,设置主键
* 调用 CrudRepository
*/
@Test
public void update(){
Book b = new Book("Spring入门","javabb1");
b.setId(3);
Book newB=bookDao.save(b);
System.out.println("update:"+newB);
}
/**
* 更新 update , 用save方法,设置主键
* 自定义SQL更新
*/
@Test
public void updateName(){
int num=bookDao.updateName(3,"Javabb3");
System.out.println("updateName:"+num);
}
/**
* 删除
* 只要有主键,直接传入主键值或者带主键值的实体都可以
*/
@Test
public void delete(){
//deleteById
//bookDao.delete(3);
//Book book = new Book("Spring入门","javabb1");
Book book = new Book();
book.setId(7);
bookDao.delete(book);
}
}