jpa使用
-
导包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
-
配置jpa
这里使用的是yml,xml类似自行配置 spring: datasource: url: jdbc:mysql://127.0.0.1:3306/goodsmanager username: root password: root driver-class-name: com.mysql.jdbc.Driver jpa: hibernate: ddl-auto: update show-sql: true database-platform: org.hibernate.dialect.MySQL5Dialect
-
创建数据库映射对象
@Entity //定义数据库对应表名为t_style,styleName内容唯一 @Table(name = "t_style",uniqueConstraints = {@UniqueConstraint(columnNames="styleName")}) public class Style { //定义该属性为主键,且自增 @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private Integer id; private String styleName; public Style() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getStyleName() { return styleName; } public void setStyleName(String styleName) { this.styleName = styleName; } }
-
创建仓库
public interface StyleRepository extends JpaRepository<Style,Integer> { //Repository自带了很多常用的方法,如果不符合需求则在这里自定义sql @Query(value="select * from t_style where style_name = :name limit 1",nativeQuery=true) Style styleByName(@Param("name") String name); //这个方法起始有自带了,但是这里写个实例,如果要扩展用这种形式,善用快捷键 Page<Style> findById(Integer, Pageable pageable); }
-
获取数据
@Autowired private StyleRepository styleRepository; //findAll查询全部 public List<Style> styleList() { return styleRepository.findAll(); } //findById根据Id来查询 public Style styleFindOne(Integer id) { return styleRepository.findById(id).get(); } //styleByName根据name查询 public Style styleByName(String name) { return styleRepository.styleByName(name); } //save保存数据,返回保存后的对象 public Style addStyle(String styleName) { Style style = new Style(); style.setStyleName(styleName); return styleRepository.save(style); } //save保存数据,返回保存后的对象,传入id是则为更新 public void styleUpdate(Integer id, String styleName) { Style style = styleRepository.findById(id).get(); style.setStyleName(styleName); style.setId(id); styleRepository.save(style); } //deleteById根据id删除数据 public void styleDel(Integer id) { styleRepository.deleteById(id); }
网友评论