我能够使用hibernate在关系数据库中持久化对象。 请看下面的代码。
package one;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SecondaryTable;
import javax.persistence.Table;
@Entity
public class Customer {
@Id
private int customerId;
private String customerName;
private String customerAddress;
private int creditScore;
private int rewardPoints;
public Customer()
{
}
public Customer(int customerId,String customerName,String customerAddress,int creditScore,int rewardsPoints)
{
this.customerId=customerId;
this.customerAddress=customerAddress;
this.creditScore=creditScore;
this.customerName=customerName;
this.rewardPoints=rewardsPoints;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
public int getCreditScore() {
return creditScore;
}
public void setCreditScore(int creditScore) {
this.creditScore = creditScore;
}
public int getRewardPoints() {
return rewardPoints;
}
public void setRewardPoints(int rewardPoints) {
this.rewardPoints = rewardPoints;
}
}
然后保存这个类的对象我使用了下面的类。下面的类创建Customer类的对象并将该对象保存在数据库中,然后再次检索它并打印每个已保存对象的CustomerName属性。
package one;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class TestCustomer {
public static void main(String args[])
{
Customer cust = new Customer(13,"Sara","Banglore",9000,60);
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
session.save(cust);
session.getTransaction().commit();
session.close();
session = factory.openSession();
session.beginTransaction();
List list = session.createQuery("FROM Customer").list();
Iterator iterator = list.iterator();
while(iterator.hasNext())
{
Customer custA = (Customer)iterator.next();
System.out.println("First Name\t"+custA.getCustomerName());
}
session.getTransaction().commit();
session.close();
}
}
我在代码上执行了很多次。代码运行正常。它能够获取所有保存的对象。
但后来我使用了oracle toad并发出sql
语句作为
Insert into Customer(CUSTOMERID,CREDITSCORE,CUSTOMERNAME,REWARDPOINTS,CUSTOMERADDRESS)
VALUES(87,4000,'Saurabh',20,'Kalwa');
记录存储在表中但是当我执行上面的代码时,我无法获取此记录。
我可以得出的一个结论是hibernate只返回persisted objects
,但是还有其他方法可以获得所有记录吗?
答案 0 :(得分:2)
使用JPA的一些建议: