我搜索了很多,仍然没有找到任何解决方案因此在这里发布了一个问题..
我正在使用lombok开发多对多关系示例。我只想为四个中的两个字段创建参数构造函数。我们怎么做到这一点?
@Data
@Entity
@Table(name = "stock")
public class Stock implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "STOCK_ID", unique = true, nullable = false)
private Integer stockId;
@Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
private String stockCode;
@Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
private String stockName;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "stock_category", joinColumns = {
@JoinColumn(name = "STOCK_ID", nullable = false, updatable = false)},
inverseJoinColumns = {@JoinColumn(name = "CATEGORY_ID", nullable = false, updatable = false)})
private Set<Category> categories = new HashSet<Category>(0);
}
分类
@Data
@RequiredArgsConstructor(staticName = "of")
@Entity
@Table(name = "category")
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "CATEGORY_ID", unique = true, nullable = false)
private Integer categoryId;
@Column(name = "NAME", nullable = false, length = 10)
@NonNull
private String name;
@Column(name = "[DESC]", nullable = false)
@NonNull
private String desc;
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "categories")
private Set<Stock> stocks = new HashSet<Stock>(0);
}
App.java
为什么我无法设置限制字段构造函数
public class App {
public static void main(String[] args) {
System.out.println("Hello World!");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Stock stock = new Stock();
stock.setStockCode("7052");
stock.setStockName("PADINI");
Category category1 = new Category("CONSUMER", "CONSUMER COMPANY");
Category category2 = new Category("INVESTMENT", "INVESTMENT COMPANY");
Set<Category> categories = new HashSet<Category>();
categories.add(category1);
categories.add(category2);
stock.setCategories(categories);
session.save(stock);
session.getTransaction().commit();
System.out.println("Done");
}
}
答案 0 :(得分:1)
原因是
如果
staticName
设置,生成的构造函数将是私有的,另外还有 static'constructor'是使用相同的参数列表生成的 包装真正的构造函数。
请不要忘记@NoArgsConstructor
,因为Hibernate需要它。