[英]Unable to insert data into database properly using Hibernate
我最近開始使用Hibernate。 我面臨以下問題
說明:對於對象客戶,當我嘗試使用hibernate saveOrUpdate將數據插入數據庫時,它將刪除客戶表中的所有條目,並僅將新行插入新數據。 我無法弄清楚是什么原因引起的。 如果嘗試通過在session.saveOrUpdate(customer)之后添加具有不同唯一代碼的新Customer對象(即customer1)來同時插入另一個數據,則我正在獲取標識符已存在的異常。
數據庫中表的定義如下
create table customer(
code varchar(100) not null,
name varchar(100) not null,
address varchar(1000) not null,
phone1 varchar(100) not null,
phone2 varchar(100),
credit_limit double default 0,
current_credit double default 0,
primary key ( code )
);
定義的Java對象如下
package com.jwt.hibernate.bean;
import java.io.Serializable;
public class Customer implements Serializable{
/**
*
*/
private static final long serialVersionUID = 2590997804699225005L;
private String code;
private String name;
private String address;
private String phone1;
private String phone2;
private Double creditLimit;
private Double currentCredit;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone1() {
return phone1;
}
public void setPhone1(String phone1) {
this.phone1 = phone1;
}
public String getPhone2() {
return phone2;
}
public void setPhone2(String phone2) {
this.phone2 = phone2;
}
public Double getCreditLimit() {
return creditLimit;
}
public void setCreditLimit(Double creditLimit) {
this.creditLimit = creditLimit;
}
public Double getCurrentCredit() {
return currentCredit;
}
public void setCurrentCredit(Double currentCredit) {
this.currentCredit = currentCredit;
}
}
執行休眠操作的類如下
package com.jwt.hibernate.dao;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.jwt.hibernate.bean.Customer;
public class CustomerDAO {
public boolean save(Customer customer){
try{
// 1. configuring hibernate
Configuration configuration = new Configuration().configure();
// 2. create sessionfactory
SessionFactory sessionFactory = configuration.buildSessionFactory();
// 3. Get Session object
Session session = sessionFactory.openSession();
// 4. Starting Transaction
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(customer);
transaction.commit();
session.close();
sessionFactory.close();
} catch (HibernateException e) {
System.out.println(e.getMessage());
System.out.println("error");
}
finally{
}
return true;
}
}
Hibernate的配置XML如下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.jwt.hibernate.bean.Customer" table="CUSTOMER">
<id column="CODE" name="code" type="java.lang.String" />
<property column="NAME" name="name" type="java.lang.String" />
<property column="ADDRESS" name="address" type="java.lang.String" />
<property column="PHONE1" name="phone1" type="java.lang.String" />
<property column="PHONE2" name="phone2" type="java.lang.String" />
<property column="CREDIT_LIMIT" name="creditLimit" type="java.lang.Double" />
<property column="CURRENT_LIMIT" name="currentCredit" type="java.lang.Double" />
</class>
</hibernate-mapping>
正在處理請求的Servlet如下
package com.jwt.hibernate.controller;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jwt.hibernate.bean.Customer;
import com.jwt.hibernate.dao.CustomerDAO;
public class CustomerControllerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ObjectInputStream in = new ObjectInputStream(request.getInputStream());
try {
Object object = (Object) in.readObject();
in.close();
String action = request.getParameter("action");
if(action!= null && action.equals("save")){
save(object, response);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void save(Object object, HttpServletResponse response) throws IOException{
Customer customer = (Customer) object;
try {
CustomerDAO customerDAO = new CustomerDAO();
customerDAO.save(customer);
ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
oos.writeObject(customer);
oos.flush();
oos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
發送對象以保存到數據庫的客戶端代碼如下
public static Object save(Object object,int objectType)
{
URL url;
if(objectType == TYPE_CUSTOMER) {
Customer customer = (Customer) object;
try {
url = new URL("http://localhost:8080/CrossoverServer/Customer?action=save");
urlCon = (HttpURLConnection) url.openConnection();
urlCon.setDoOutput(true); // to be able to write.
urlCon.setDoInput(true); // to be able to read.
out = new ObjectOutputStream(urlCon.getOutputStream());
out.writeObject(customer);
out.close();
ObjectInputStream ois = new ObjectInputStream(urlCon.getInputStream());
customer = (Customer) ois.readObject();
ois.close();
return customer;
} catch (IOException e) {
e.printStackTrace();
}
catch ( ClassNotFoundException e2) {
e2.printStackTrace();
}
}
return null;
}
客戶對象的創建方式如下
public Object guiToObject()
{
Customer customer = new Customer();
customer.setCode(txtCode.getText());
customer.setName(txtName.getText());
customer.setAddress(txtAddress.getText());
customer.setPhone1(txtPhone1.getText());
customer.setPhone2(txtPhone2.getText());
customer.setCreditLimit((Double) Double.parseDouble(txtCreditLimit.getText()));
if(txtCurrentCredit.getText() != null && !txtCurrentCredit.getText().trim().isEmpty())
customer.setCurrentCredit((Double) Double.parseDouble(txtCurrentCredit.getText().trim()));
else
customer.setCurrentCredit(0.0);
return customer;
}
請問有人可以幫我以上將新行插入客戶表的方法出了什么問題嗎?
謝謝。
可能的原因可能是您的代碼重新創建了表,並添加了記錄后記。
您是否嘗試過調試,並在插入數據庫之前查看數據庫方面的情況?
旁注; 您的finally塊為空白。 您應該關閉會話,並在finally塊中編寫類似的代碼。
感謝他的快速回復。
我弄清楚了原因。
將hibernate.cfg.xml中的以下屬性從“創建”更改為“驗證”可以解決該問題。
驗證
謝謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.