标签:style class blog code java http
Hibernate的多对一操作:
例子参考引用:
http://www.tutorialspoint.com/hibernate/hibernate_many_to_one_mapping.htm
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://127.0.0.1/testdb</property> <property name="connection.username">root</property> <property name="connection.password"></property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- Enable Hibernate‘s automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">update</property> <mapping resource="com/my/hbm/User.hbm.xml"/> <mapping resource="com/my/hbm/UserAccount.hbm.xml"/> </session-factory> </hibernate-configuration>
User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.my.bean.User" table="user"> <id name="id" type="int"> <column name="id" /> <generator class="native" /> </id> <property name="name" type="java.lang.String" length="50"> <column name="name" not-null="true" length="50" /> </property> <property name="age" type="int"> <column name="age" /> </property> <property name="password" type="java.lang.String" length="50"> <column name="password" length="50" /> </property> <property name="email" type="java.lang.String" length="100"> <column name="email" length="100" /> </property> <property name="createtime" type="java.util.Date"> <column name="createtime" /> </property> </class> </hibernate-mapping>
UserAccount.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.my.bean.UserAccount" table="user_account"> <id name="id" type="int"> <column name="id" /> <generator class="native" /> </id> <many-to-one name="user" column="user_id" class="com.my.bean.User" not-null="true"></many-to-one> <property name="account" type="java.lang.String" length="50"> <column name="account" not-null="true" length="50" /> </property> </class> </hibernate-mapping>
Java Bean: User.java
package com.my.bean; import java.util.Date; public class User { private int id; private String name; private int age; private String password; private String email; private Date createtime; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getCreatetime() { return createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } }
Java Bean: UserAccount.java
package com.my.bean; public class UserAccount { private int id; private String account; private User user; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
HibernateUtil.java
package com.my.dao.util; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml Configuration configuration = new Configuration(); return configuration.configure().buildSessionFactory( new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build()); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }
测试:
package com.my.init; import java.util.Date; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import com.my.bean.User; import com.my.bean.UserAccount; import com.my.dao.util.HibernateUtil; public class Test { public static void main(String[] args) { Test t = new Test(); // Add new user User user = t .addUser("robin", "abcd1234", "robin@88db.com", new Date()); System.out.println(user.getId()); // Get user list List<User> users = t.listUser(); for (User item : users) { System.out.println("User name: " + item.getName()); } // Add UserAccount UserAccount ua = t.addUserAccount("robinzhang", user); System.out.println("Add UserAccount: " + ua.getId()); // Update UserAccount UserAccount ua_u = t.updateUserAccount(ua.getId(), "robin_zhang"); System.out.println("Update UserAccount: " + ua_u.getAccount()); // Get User Account List List<UserAccount> uas = t.listUserAccount(); for (UserAccount item : uas) { System.out.println("UserAccount: " + item.getAccount()); System.out.println("UserID: " + item.getUser().getId()); } // Delete UserAccount boolean result = t.deleteUserAccount(1); System.out.println("Delete UserAccount: " + result); // Delete User result = t.deleteUser(user); System.out.println("Delete User: " + result); } /** * List Users */ @SuppressWarnings("unchecked") public List<User> listUser() { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); List<User> users = null; try { // Select action String hqlSelect = "from User where name like :name"; Query query = session.createQuery(hqlSelect); query.setParameter("name", "%ro%"); users = query.list(); session.getTransaction().commit(); } catch (HibernateException e) { if (session.getTransaction() != null) session.getTransaction().rollback(); e.printStackTrace(); } finally { session.close(); } return users; } /** * Add new user * * @param name * User name * @param password * User password * @param email * User email * @param createtime * User create time * @return User object */ public User addUser(String name, String password, String email, Date createtime) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); User u = new User(); try { u.setName(name); u.setPassword(password); u.setCreatetime(createtime); u.setEmail(email); u.setAge(18); // Get new user id Integer userid = (Integer) session.save(u); session.getTransaction().commit(); } catch (HibernateException e) { if (session.getTransaction() != null) session.getTransaction().rollback(); e.printStackTrace(); } finally { session.close(); } return u; } /** * Get UserAccount Object * * @param account * account name * @param user * User ID * @return UserAccount object */ public UserAccount addUserAccount(String account, User user) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); UserAccount ua = null; try { ua = new UserAccount(); ua.setAccount(account); ua.setUser(user); session.save(ua); session.getTransaction().commit(); } catch (HibernateException e) { if (session.getTransaction() != null) session.getTransaction().rollback(); e.printStackTrace(); } finally { session.close(); } return ua; } /** * Get User Account List * * @return */ @SuppressWarnings("unchecked") public List<UserAccount> listUserAccount() { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); List<UserAccount> uas = null; try { String hqlSelect = "from UserAccount where account like :account"; Query query = session.createQuery(hqlSelect); query.setParameter("account", "%ro%"); uas = query.list(); session.getTransaction().commit(); } catch (HibernateException e) { if (session.getTransaction() != null) session.getTransaction().rollback(); e.printStackTrace(); } finally { session.close(); } return uas; } /** * Update User Account * * @param id * @param account */ public UserAccount updateUserAccount(Integer id, String account) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); UserAccount ua = null; try { ua = (UserAccount) session.get(UserAccount.class, id); ua.setAccount(account); session.update(ua); session.getTransaction().commit(); } catch (HibernateException e) { if (session.getTransaction() != null) session.getTransaction().rollback(); e.printStackTrace(); } finally { session.close(); } return ua; } /** * Delete UserAccount * * @param id * @return true/false */ public boolean deleteUserAccount(Integer id) { boolean result = false; Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); try { UserAccount ua = (UserAccount) session.get(UserAccount.class, id); session.delete(ua); session.getTransaction().commit(); result = true; } catch (HibernateException e) { if (session.getTransaction() != null) session.getTransaction().rollback(); e.printStackTrace(); } finally { session.close(); } return result; } /** * Delete User * * @param user * @return */ public boolean deleteUser(User user) { boolean result = false; Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); try { session.delete(user); session.getTransaction().commit(); result = true; } catch (HibernateException e) { if (session.getTransaction() != null) session.getTransaction().rollback(); e.printStackTrace(); } finally { session.close(); } return result; } }
使用Hibernate会自动建库。
[Hibernate] - many to one,布布扣,bubuko.com
标签:style class blog code java http
原文地址:http://www.cnblogs.com/HD/p/3799335.html