我很困惑,我正在试图找出为什么我在数据库中使用以下代码创建了两个客户而没有运气。我试图从代码中删除所有噪音,我希望我没有删除任何重要的解决问题。 按以下顺序排列:实体,DAO,服务和带有 specialTreatment 的 SpecialService ,其中包含虚假行为。
在 specialTreatment 中,目标是获取一个没有客户链接的现有订单,创建一个新客户,并将其与订单相关联。
实体:
Order.java:
@Entity
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "pk_id_order")
private Integer id;
// Other fields ...
@BatchFetch(value = BatchFetchType.IN)
@JoinColumn(name = "fk_id_customer", referencedColumnName = "pk_id_customer")
@ManyToOne(fetch = FetchType.LAZY, optional = false)
private Customer customer;
// Other fields ...
// Getter & setters for each field
@Override
public int hashCode() {
int hash = 7;
hash = 79 * hash + (this.id != null ? this.id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Order)) {
return false;
}
final Order other = (Order) obj;
if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) {
return false;
}
return true;
}
}
Customer.java:
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "pk_id_customer")
private Integer id;
// Other fields
@OrderBy(value = "createdAt DESC")
@OneToMany(mappedBy = "customer", fetch = FetchType.LAZY)
private List<Order> orders;
@Override
public int hashCode() {
return (id != null ? id.hashCode() : 0);
}
@Override
public boolean equals(Object object) {
if (object == null || !(object instanceof Customer)) {
return false;
}
final Customer other = (Customer) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
}
DAOs:
@Repository
@Transactional
public class CustomerDao {
@PersistenceContext
protected EntityManager em;
public void create(Customer customer) {
this.em.persist(customer);
}
}
@Repository
@Transactional
public class OrderDao {
@PersistenceContext
protected EntityManager em;
public Order edit(Order order) {
return this.em.merge(order);
}
}
服务:
@Service
@Transactional
public class CustomerService {
@Autowired
private CustomerDao customerDao;
public void create(Customer customer) {
this.customerDao.create(customer);
}
}
@Service
@Transactional
public class OrderService {
@Autowired
private OrderDao orderDao;
public void edit(Order order) {
this.orderDao.edit(order);
}
}
@Service
@Transactional
public class SpecialService {
@Autowired
private CustomerService customerService;
@Autowired
private OrderService orderService;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void specialTreatment(Order order) {
Customer customer = new Customer();
// Fill customer ...
this.customerService.create(customer); // LINE X
order.setCustomer(customer); // LINE Y
this.orderService.edit(order);
}
}
注意: 评论第X行时: - 没有客户创建(按预期),订单按预期编辑 评论Y行时: - 客户按预期创建(仅一行),但未链接到我的订单
从Spring MVC控制器调用代码
有什么建议吗?