方式一
复合主键类
@Embeddable public class UserKey implements Serializable { @Column(name = "NAME", nullable = false, length = 32) private String name; @Column(name = "AGE", nullable = true, length = 32) private String age; getter/setter... }
实体类
@Entity @Table(name = "USER") @IdClass(UserKey.class) public class User implements Serializable { /** * serialVersionUID */ private static final long serialVersionUID = -7768637914227571159L; /** * 物料编码 */ @Id @Column(name = "NAME", nullable = true, length = 32) private String name; /** * 技术规范书编码 */ @Id @Column(name = "AGE", nullable = true, length = 32) private String age; getter/setter }
查找方法
userRepository.findOne(userKey);
参考:https://www.cnblogs.com/boywwj/p/8031106.html
方式二
复合主键不能用 @Id,需要用 @EmbeddedId
主键类
@Embeddable public class UserFundPrimarykey implements Serializable { private static final long serialVersionUID = 1L; // 用户 ID private Integer userId; private String date; getter/setter... }
实体类
@Entity @Table(name = "user_funds") public class UserFund { /** * 主键 * 复合主键不能用 @Id,需要用 @EmbeddedId。插入数据的时候必须手工赋值 */ @EmbeddedId private UserFundPrimarykey userFundPK; // 本金 @Column(precision=18, scale=5) private BigDecimal principal; // 利率(5% 传 0.05) @Column(precision=18, scale=5) private BigDecimal rate; /** * 当天收益(日利息 = 本金 * 利率 /365) * 保留 2 位小数 */ @Column(precision=18, scale=2) private BigDecimal interest; getter/setter... }
持久层
public interface UserFundRepository extends CrudRepository<UserFund, UserFundPrimarykey> {}
设值使用
UserFund uf2 = new UserFund(); // 必须手动设置主键 uf2.setUserFundPK(new UserFundPrimarykey(2, "2017-07-01")); uf2.setRate(new BigDecimal("0.041")); uf2.setPrincipal(new BigDecimal("20000")); // 截断,只保留两位小数 uf2.setInterest(uf2.getRate().multiply(uf2.getPrincipal()).divide(new BigDecimal("365"), 2, RoundingMode.DOWN)); userFundRepository.save(uf2);
参考:https://blog.csdn.net/mn960mn/article/details/74034512
目录
方式一
方式二
目录
方式一
方式二