public class ContactManager {
public static void main(String[] args) {
// loads configuration and creates a session factory
Configuration configuration = new Configuration().configure();
ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
registry.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
// opens a new session from the session factory
Session session = sessionFactory.openSession();
session.beginTransaction();
// persists two new Contact objects
Contact contact1 = new Contact("Nam", "hainatu@gmail.com", "Vietnam", "0904277091");
session.persist(contact1);
Contact contact2 = new Contact("Bill", "bill@gmail.com", "USA", "18001900");
Serializable id = session.save(contact2);
System.out.println("created id: " + id);
// loads a new object from database
Contact contact3 = (Contact) session.get(Contact.class, new Integer(1));
if (contact3 == null) {
System.out.println("There is no Contact object with id=1");
} else {
System.out.println("Contact3's name: " + contact3.getName());
}
// loads an object which is assumed exists
Contact contact4 = (Contact) session.load(Contact.class, new Integer(1));
System.out.println("Contact4's name: " + contact4.getName());
// updates a loaded instance of a Contact object
Contact contact5 = (Contact) session.load(Contact.class, new Integer(2));
contact5.setEmail("info1@company.com");
contact5.setTelephone("1234567890");
session.update(contact5);
错误:
Hibernate: select max(CONTACT_ID) from CONTACT
created id: 2
Contact3's name: Nam
Contact4's name: Nam
Hibernate: select contact0_.CONTACT_ID as CONTACT1_0_0_, contact0_.NAME as NAME0_0_, contact0_.email as email0_0_, contact0_.address as address0_0_, contact0_.telephone as telephone0_0_ from CONTACT contact0_ where contact0_.CONTACT_ID=?
Exception in thread "main" org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.mycompany.Contact#8]
答案 0 :(得分:0)
使用id
方法中session.save(contact2)
返回的load()
将其从数据库中恢复。它应该工作。
Contact contact5 = (Contact) session.load(Contact.class, id);