有两个表Appointment和Auto_User,约会具有user_id作为外键,当我尝试保存约会(从数据库获取用户数据后)时,它抛出:“ PersistentObjectException:传递给持久对象的分离实体:AutoUser”
下面是代码:
Appointment.java-
@Entity
@Table(name = "APPOINTMENT")
public class Appointment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "APPOINTMENT_ID")
private Long appointmentId;
@ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn(name = "USER_ID")
private AutoUser user;
getters/setters..
}
AutoUser.java
@Entity
@Table(name="AUTO_USER")
public class AutoUser {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long autoUserId;
@Column(name="FIRST_NAME")
private String firstName;
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="autoservice" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect"
value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
AppointmentController.java
@ResponseBody
@RequestMapping(value="/save", method=RequestMethod.POST)
public List<Appointment> saveAppointment(@ModelAttribute Appointment appointment)
{
String userName = SecurityContextHolder.getContext().getAuthentication().getName();
appointmentService.createNewAppointment(appointment, userName);
return this.appointmentRepository.findAll();
}
AppoitmentServiceImpl.java
@Service("appointmentService")
public class AppoitmentServiceImpl implements AppointmentService {
@Autowired
private AutoUserRepository autoUserRepository;
@Autowired
private AppointmentRepository appointmentRepository;
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void createNewAppointment(Appointment appointment, String userName) {
AutoUser user = autoUserRepository.findByUsername(userName);
appointment.setUser(user);
appointment.setStatus("Initial");
appointmentRepository.save(appointment); //getting exception here
}
}
AppointmentRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
public interface AppointmentRepository extends JpaRepository<Appointment, Long> {
}
AutoUserRepository.java
public interface AutoUserRepository extends JpaRepository<AutoUser, Long> {
public AutoUser findByUsername(String userName);
}
对此表示感谢,