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

Source: Internet
Author: User
Tags object object

In the previous article, we created the Hibernateconfigurationutil class, which can be used to obtain information about the table name and column name of the entity class, and we will use the Hibernateconfigurationutil class as well as the Java reflection in this article. To implement a JDBCUITL tool class that implements functions similar to Session.save (Object object) in Hibernate

Jdbcutil class

Package Util;import Java.lang.reflect.field;import Java.sql.connection;import java.sql.preparedstatement;import Java.sql.timestamp;import java.util.arraylist;import Java.util.date;import Java.util.list;public class JDBCUtil {/** * Use reflection +JDBC to implement an action similar to Session.save (Object object), for primary key is a single self-increment primary key * Here is just an implementation idea that can be extended as needed and implemented similar update, delete, get operations * @ param Connection Database connection * @param entity class to be saved * @throws Exception */public static <T> void Save (Connection connecti On, T entity) throws Exception {class<? extends object> clazz = Entity.getclass (); field[] fields = Clazz.getdeclaredfields (); StringBuilder builder = new StringBuilder (); Builder.append ("INSERT into"); Builder.append ( Hibernateconfigurationutil.gettablename (Clazz)); Builder.append ("("); list<field> usefields = new arraylist<field> (); Field field = null;for (int i = 0; i < fields.length; i++) {//setting field can be accessed, if this option is not set, the private field cannot be accessed field = Fields[i];field.s Etaccessible (TRUE);//Filters unwanted properties, if ("id". Equals (Field.getname ()) {continue;} Usefields.add (field); Builder.append (Hibernateconfigurationutil.getcolumnname (Clazz,field.getname ())); if (I < fields.length-1) Builder.append (",");} Builder.append (") VALUES ("); for (int i = 0; I < usefields.size (); i++) {builder.append ("?"); if (I < usefields.size ()-1) {Builder.append (",");} else {builder.append (")");}} PreparedStatement pstmt = connection.preparestatement (builder.tostring ()); class<?> clazz2 = null;for (int i = 0; i < usefields.size (); i++) {field = Usefields.get (i);//Set the value of the corresponding type according to the type of the field CLA ZZ2 = Field.gettype (); if (clazz2 = = String.class) {pstmt.setstring (i + 1, field.get (entity). ToString ()); continue;} if (clazz2 = = Integer.class | | clazz2 = = int.class) {pstmt.setint (i + 1, field.getint (entity)); continue;} if (clazz2 = = Double.class | | clazz2 = = double.class) {pstmt.setdouble (i + 1, field.getdouble (entity)); continue;} if (clazz2 = = Date.class) {Date date = (date) Field.get (entity);p Stmt.settimestamp (i+1, New Timestamp (Date.gettime ())); ConTinue;}} Pstmt.executeupdate ();}}


User class

Package Bean;import Java.util.date;public class User {private int id;private string Username;private string Password;priv ate int intvalue;private double doublevalue;private Date datevalue;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;} public int Getintvalue () {return intvalue;} public void Setintvalue (int intvalue) {this.intvalue = Intvalue;} Public double Getdoublevalue () {return doublevalue;} public void Setdoublevalue (double doublevalue) {this.doublevalue = Doublevalue;} Public Date Getdatevalue () {return dateValue;} public void Setdatevalue (Date dateValue) {this.datevalue = DateValue;}}


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 ">
Userdao

Package Dao;import Bean. User;public interface Userdao {public void AddUser (user user);

Userdaoimpl

Package Dao.impl;import Java.sql.connection;import Java.sql.sqlexception;import java.util.date;import Org.hibernate.session;import org.hibernate.sessionfactory;import org.hibernate.jdbc.work;import util. Jdbcutil;import Bean. User;import DAO. Userdao;public class Userdaoimpl implements Userdao {private sessionfactory sessionfactory; @Overridepublic void AddUser (Final user user) {Session session = Sessionfactory.getcurrentsession (); Session.dowork (new work () {@Overridepublic void execute ( Connection Connection) throws SQLException {try {jdbcutil.save (Connection, user);} catch (Exception e) { E.printstacktrace ();}});} Public Sessionfactory Getsessionfactory () {return sessionfactory;} public void Setsessionfactory (Sessionfactory sessionfactory) {this.sessionfactory = Sessionfactory;}}


Applicationcontext.xml

Note: The transaction must be configured in Hibernate4, otherwise the above sessionfactory.getcurrentsession () will not be able to fetch the value

<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><!-- Configure transaction--><bean id= "TransactionManager" class= "Org.springframework.orm.hibernate4.HibernateTransactionManager "><property name=" sessionfactory "><ref local=" Sessionfactory "/></property></bean>< !--Configure the propagation characteristics of a transaction--><tx:advice id= "Txadvice" transaction-manager= "TransactionManager" ><tx:attributes> <tx:method name= "add*" propagation= "REQUIRED"/><tx:method name= "del*" propagation= "REQUIRED"/> <tx:method name= "update*" propagation= "REQUIRED"/><tx:method name= "*" read-only= "true"/&GT;&LT;/TX: attributes></tx:advice><!--Configure classes and methods that participate in transactions--><aop:config><aop:pointcut expression= " Execution (* dao.impl.*.* (..)) " Id= "Allservicemethod"/><aop:advisor advice-ref= "Txadvice" pointcut-ref= "Allservicemethod"/&GT;&LT;/AOP: Config><bean id= "Userdao" class= "Dao.impl.UserDaoImpl" ><property name= "sessionfactory" ref= " Sessionfactory "/></bean>


Here is the test code:

Package Test;import Java.util.date;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Bean. User;import DAO. Userdao;public class Testjdbcutil {@SuppressWarnings ("resource") public static void main (string[] args) { ApplicationContext context =  new Classpathxmlapplicationcontext ("Applicationcontext.xml"); Userdao Userdao = (Userdao) context.getbean ("Userdao"); User user = new user (), User.setusername ("name"), User.setpassword ("password"); User.setintvalue (2); User.setdoublevalue (4.0); User.setdatevalue (new Date ()); Userdao.adduser (user);}}

Note: The database used is mysql,hibernate version 4.2.12.Final





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

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.