目录
1、springboots使用Jpa连接数据需要的依赖:
<!--jpa依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Mysql依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2、创建实体Bean
@Entity
@Table(name="t_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "name")
private String name;
@Column
private int age;
@Column
private int sex;
@Column
private String address;
省略get...set方法
- @Entity:表明是一个实体Bean
- @Table:自定义表名
- @Id:标明主键
- @GeneratedValue:主键自增,使用该注解在创建bi表的时候会同步创建一个hibernate-sequence表来记录下一个主键
- @Column:定义列,可以自定义列名,指定列的类型以及一些约束
3、创建一个Repository
创建的所有的Repository都要继承JpaRepository,因为JpaRepository中已经给我们封装一系列的增删改查方法
public interface UserRepository extends JpaRepository<User,Long> {
User findByName(String name);
User findByNameAndAge(String name,int age);
@Query(value = "select * from t_user t where t.id =?1",nativeQuery = true)
User findUserForSql(Long id);
@Query(value = "select t from User t where t.id =?1")
User findUserForHql(Long id);
@Query(value = "select t from User t where t.id = :id")
User findUserForHql2(@Param("id")Long id);
@Modifying
@Query(value = "delete from User where id = ?1")
void deleteUser(Long id);
@Modifying
@Query(value = "update User set name = ?1 where id = ?2")
void updateUser(String name,Long id);
}
4、配置连接数据库的配置文件
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/test?useSSL=false
username: root
password: ****
driver-class-name: com.mysql.jdbc.Driver
jpa:
database: mysql
show-sql: true
hibernate:
ddl-auto: update
以上就完成了springboot使用jpa连接数据库的基本操作