[英]Fetching data from table using hibernate
我能够使用 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
,但还有其他方法可以获得所有记录吗?
以及一些使用 JPA 的建议:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.