delete删除执行不生效
增加注解@Transactional 和@Modifying
@Query(value = "delete from xxx where xxxx= ?1", nativeQuery = true)查询时循环嵌套导致栈溢出
在A的类里增加B中的a属性
如User.java, Role.java
则User.java中增加
@JsonIgnoreProperties(value = {“user”})
表无主键(配置组合主键)
https://www.jianshu.com/p/b44d01d50222JPA级联删除不生效
被关联对象增加注解
@OnDelete(action = OnDeleteAction.CASCADE)联合主键
@IdClass(DAOPK.class)
其中DAOPK的属性为联合主键的属性集,要重写equals和hashCode,DAO根据DAOPK的所有属性集是否 完全相同来判断是否是同一条数据。主键生成策略:
GenerationType中可选择的策略:
— IDENTITY:采用数据库ID自增长的方式来自增主键字段,部分版本的Oracle不支持;
— AUTO:JPA自动选择合适的策略,是默认选项;
— SEQUENCE:通过序列产生主键,通过@SequenceGenerator注解指定序列名,MySql不支持这种方式。
— TABLE:通过表产生键,框架借助由表模拟序列产生主键,使用该策略可以使应用更易于数据库移植。
- 删除deleteById不生效:
CrudRepository.delete(Entity entity)和CrudRepository.deleteById(Long id)不生效,但是 CrudRepository.deleteByUserId(Long Id)就可以,其中delete和deleteById是JPA自带的,deleteByUserId代 码如下:
@Transactional
@Modifying
@Query(value = "delete from user where user_id=?1", nativeQuery = true)
void deleteByUserId(Long Id)
原因还没找到,暂时使用原生SQL。
- 一对一级联删除配置:
主表:User
从表:UserDetail
主表对应的类设置:
optional = false, mappedBy = "user"
public class User
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
@Column(columnDefinition = "char(80) COLLATE utf8_general_ci")
private String userName;
@OneToOne(optional = false, mappedBy = "user", fetch = FetchType.LAZY)
@JoinColumn(name="userId")
private UserDetail userDetail ;
}
从表对应的类配置:
@PrimaryKeyJoinColumn不可省略,@OnDelete(action = OnDeleteAction.CASCADE)写在从表的类即可
public class UserDetail
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
@Column(columnDefinition = "char(80) COLLATE utf8_general_ci")
private String phoneNumber;
@Column(columnDefinition = "char(255) COLLATE utf8_general_ci")
private String address;
@OneToOne(optional = false, fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
@OnDelete(action = OnDeleteAction.CASCADE)
@JoinColumn(name="userId")
private User user;
}
- Unable to find xxx with id异常:
在主表对应字段增加
@NotFound(action = NotFoundAction.IGNORE) ,optional = true 二者缺一不可