我似乎无法向表中添加值。没有错误,但是值未插入我的数据库中。提交表格后,不会显示任何错误。
查看控制台后,显示:
Hibernate:
insert
into
referral
(address, doctor_contact_no, doctor_name, facility_contact_no, facility_type, referral_no, referring_from, referring_to)
values
(?, ?, ?, ?, ?, ?, ?, ?)
我已经尝试记录日志,以防万一我的控制器无法读取我提交的表单。
我正在保存的实体/模型的代码片段
@Entity
@Table(name="referral")
public class Referrals {
@Id
@Column
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@Column
private String referral_no;
@Column
private String facility_contact_no;
@Column
private String referring_from;
@Column
private String referring_to;
@Column
private String facility_type;
@Column
private String address;
@Column
private String doctor_name;
@Column
private String doctor_contact_no;'
我的服务类别的代码段
@Service
@Transactional
public class ReferralServicesImpl implements ReferralServices{
@Autowired
private ReferralDao referralDao;
public List<Referrals> list(){
return referralDao.list();
}
public boolean saveReferral(Referrals referral){
if(referralDao.saveReferral(referral))
return true;
else
return false;
}
}
控制器方法的代码片段
@RequestMapping(value = "/teleaudiology/referral", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("referrals", "referrals", new Referrals());
}
@RequestMapping(value = "/teleaudiology/referrals", method = RequestMethod.POST)
public String submit(@Valid @ModelAttribute("referrals")Referrals referral,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error";
}
System.out.println("referral: "+referral.getDoctor_name());
if(referralServices.saveReferral(referral))
return "redirect:../teleaudiology";
else
return "redirect:../teleaudiology";
}
这是ReferralDao类
public interface ReferralDao {
public boolean saveReferral(Referrals referral);
public List<Referrals> list();
}
推荐连结
@Repository
@Transactional
public class ReferralDaoImpl implements ReferralDao {
@Autowired
SessionFactory session;
Transaction trans;
public boolean saveReferral(Referrals referral) {
// TODO Auto-generated method stub
//System.out.println("Saving..."+referral.getReferring_to_address());
trans=session.getCurrentSession().beginTransaction();
session.getCurrentSession().saveOrUpdate(referral);
return true;
}
public List<Referrals> list() {
// TODO Auto-generated method stub
return session.getCurrentSession().createQuery("from Referrals").list();
}
}
我尝试使用
trans=session.getCurrentSession().getTransaction();
但是导致这个错误
`saveOrUpdate is not valid without active transaction`
servlet-context.xml中的片段
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="sessionFactory" />
</beans:bean>
最佳答案
尝试使用下面的代码
Session s = sessionFactory.getCurrentSession();
s.save(object);