hibernate--table name, primary key name, field name (integrated with spring) based on entity class

Source: Internet
Author: User



This document is referenced from http://blog.csdn.net/fhwbj/article/details/3267787



When using hibernate, we may sometimes need to  about the database table based on the entity class, the content of the link above has been given the template, but when using Hibernate4, if the obtained persistentclass is always null, You can try to initialize the configuration in the following way





if (configuration = = null) {configuration = new configuration (). Configure (); Configuration.buildsessionfactory ();}
The following goes to the point where hibernate and spring are integrated, if we are hibernate configured in the Spring configuration file, There is no Hibernate.cfg.xml file (the above method must have this file), then how do we get the configuration? In fact, we can get the configuration object according to the sessionfactory configured in spring, the following is the specific code implementation





Hiberanteconfigurationutil Class (Mapping tool Class)



It is important to note that:



1. When taking Sessionfactory, add the & number, the reason can see http://blog.csdn.net/zhangjk1993/article/details/40017583



2. The XML file used here is mapped to ensure that the entity class name and the corresponding mapping file name are consistent





Package Util;import Java.util.iterator;import Org.hibernate.cfg.configuration;import org.hibernate.mapping.Column; Import Org.hibernate.mapping.persistentclass;import Org.hibernate.mapping.property;import Org.springframework.beans.beansexception;import Org.springframework.context.applicationcontext;import Org.springframework.context.applicationcontextaware;import org.springframework.orm.hibernate4.localsessionfactorybean;/** * Get corresponding table name, primary key name, field name (integrated with spring) based on entity class * This is a mapping using an XML file configuration, You need to ensure that the entity class name is consistent with the corresponding mapping file name, that is, User.java and User.hbm.xml * </p> * Here uses the inheritance Applicationcontextaware way to get ApplicationContext, * It is therefore necessary to configure the class in the spring configuration file to automatically inject the ApplicationContext object * * <bean class= "util. Hibernateconfigurationutil "/> */public class Hibernateconfigurationutil implements Applicationcontextaware { private static ApplicationContext applicationcontext;private static Configuration configuration;public static Configuration GetConfiguration () {if (configuration = = null) {//Sessionfactory to be added &localsessionfactOrybean factory = (Localsessionfactorybean) applicationcontext.getbean ("&sessionfactory"); configuration = Factory.getconfiguration ();} return configuration;} private static <T> Persistentclass Getpersistentclass (class<t> clazz) {synchronized ( Hibernateconfigurationutil.class) {Persistentclass pc = GetConfiguration (). Getclassmapping (Clazz.getSimpleName ()); if (PC = = NULL) {configuration = Configuration.addclass (clazz);p C = configuration.getclassmapping (Clazz.getname ());} return PC;}} /** * Get the table name corresponding to the entity class * * @param Clazz * Class object of entity class * @return table name */public static <T> String gettablename (Cla Ss<t> clazz) {return Getpersistentclass (clazz). GetTable (). GetName (); /** * Get the primary key field name of the entity class corresponding table * * @param clazz * Class object of entity class * @return primary key field name */public static <T> String GETPKCO Lumnname (class<t> clazz) {return Getpersistentclass (clazz). GetTable (). GetPrimaryKey (). GetColumn (0). GetName ( );} /** * Gets the field name corresponding to the class attribute * * @param clazz * Class object of the entity class * @paRam PropertyName * Attribute name of entity class * @return property corresponding field name */public static <T> String getcolumnname (class<t> CLA ZZ, String propertyname) {String columnName = ""; Persistentclass Persistentclass = Getpersistentclass (clazz); property = Persistentclass.getproperty (propertyname);iterator<?> Iterator = Property.getcolumniterator (); if (Iterator.hasnext ()) {Column column = (column) iterator.next (); ColumnName + = Column.getname ();} return columnName;} @Overridepublic void Setapplicationcontext (ApplicationContext context) throws Beansexception {ApplicationContext = Context;}}







Applicationcontext.xml
<span style= "White-space:pre" ></span><bean id= "sessionfactory" class= " Org.springframework.orm.hibernate4.LocalSessionFactoryBean "><property name=" DataSource "ref=" DataSource "/ ><property name= "hibernateproperties" ><props><prop key= "Hibernate.hbm2ddl.auto" >update</ Prop><prop key= "Hibernate.show_sql" >true</prop><prop key= "Hibernate.format_sql" >true</ Prop></props></property><property name= "Mappingresources" ><list><value>bean/ User.hbm.xml</value></list></property></bean><bean class= "util. Hibernateconfigurationutil "/>

User class




Package Bean;public class User {private int id;private string username;private string password;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;}}
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 ">
Here is the test code







New Classpathxmlapplicationcontext ("Applicationcontext.xml"); System.out.println (Hibernateconfigurationutil.gettablename (User.class)); System.out.println (Hibernateconfigurationutil.getpkcolumnname (User.class)); System.out.println (Hibernateconfigurationutil.getcolumnname (User.class, "username"));


hibernate--table name, primary key name, field name (integrated with spring) based on entity class


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.