4.
添加一个实体类User,在建立的同时会在数据库中建立表user。
@Entity: 表明是一个实体类。默认情况下class 名即数据库表中表名,class 字段名即表中的字段名。若在后面加上(name=“xxx"),则对应的表为xxx。@table也可以修改对应的表。
@Data: 需要lombok插件。注解在类上, 为类提供读写属性, 此外还提供了 equals()、hashCode()、toString() 方法
@Id:声明一个实体类的属性映射为数据库的主键列
@GeneratedValue: 用于标注主键的生成策略,通过strategy 属性指定
Notes:
在application.propertities中,spring.jpa.hibernate.ddl-auto控制着表的建立,它一共有4个属性和对应的功能如下所示:
ddl-auto:create----每次运行该程序,没有表格会新建表格,表内有数据会清空
ddl-auto:create-drop----每次程序结束的时候会清空表
ddl-auto:update----每次运行程序,没有表格会新建表格,表内有数据不会清空,只会更新
ddl-auto:validate----运行程序会校验数据与数据库的字段类型是否相同,不同会报错
package cn.qmj.springboot;import lombok.Data;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;@Entity// 表示实体类@Data// 自动生成getter和setterpublicclassUser{@Id@GeneratedValueprivate Integer collegeId;private String collegeName;private String principalName;private Intger principalId;}
实现一个接口UserRepository,用于通过实体集操作数据库
JpaRepository<T,D>: T为实体类,D为主键类型
package cn.qmj.springboot;import org.springframework.data.jpa.repository.JpaRepository;publicinterfaceUserRepositoryextendsJpaRepository<User, Integer>{}
实现Controller类
@Autowired : 按照类型进行自动注入
package cn.qmj.springboot;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestControllerpublicclassUserController{@Autowiredprivate UserRepository userRepository;@GetMapping("/Users")public List<User>userList(){return userRepository.findAll();}}
打开浏览器http://localhost:8080/query,查看数据。