Multi-layered optimization problem of hibernate

Source: Internet
Author: User

When we first approached the database, even MVC was nothing. It was not until I started learning hibernate that I began to have layered thoughts. However, even with this most basic concept, the code that is written out is still relatively high in redundancy.

For example, if I want to add a user record, the code is as follows

User class:

Package entity;

public class User {

private int user_id;

Private String username;

private String password;

public int getuser_id () {
return user_id;
}

Public String GetUserName () {
return username;
}

Public String GetPassword () {
return password;
}

public void setuser_id (int user_id) {
this.user_id = user_id;
}

public void Setusername (String username) {
This.username = Username;
}

public void SetPassword (String password) {
This.password = password;
}

}

DAO interface Layer:

Public interface Iuserdao {

void Save (user user);

User Queryuserbyid (int user_id);

}

DAO implementation layer:

public class Userdaoimpl implements Iuserdao {

public void Save (user user) {
Session session = NULL;
Transaction tran = null;
try {
Session = Hibernatesessionfactory.getsession ();
Tran = Session.begintransaction ();
Session.save (user);
Tran.commit ();
} catch (Exception e) {
Tran.rollback ();
} finally {
Session.close ();
}
}

}

In this way, a simple save user's operation can be completed. It's okay at first, and I do it when I add other classes (like Product,order).

However, it can be seen that this is unreasonable. Obviously, the code redundancy is very high, if you are saving a Product object, you can imagine the code is as follows:

public class Productdaoimpl implements Iproductdao {

public void Save (product product) {
Session session = NULL;
Transaction tran = null;
try {
Session = Hibernatesessionfactory.getsession ();
Tran = Session.begintransaction ();
Session.save (product);
Tran.commit ();
} catch (Exception e) {
Tran.rollback ();
} finally {
Session.close ();
}
}

}

By comparison, the parameters are changed, and the user is replaced with product. Later, I thought, could you write these two methods into a method. Now that you can save the user and save the product, change the parameters to their common parent class (nothing is more appropriate than object).

As a result, the code is optimized as follows:

Basedao Interface:

Public interface Ibasedao {

void Save (Object object);

}

Userdao Interface:

Public interface Iuserdao {

void Save (user user);

}

Basedao Implementation class:

public class Basedaoimpl implements Ibasedao {

public void Save (object object) {
Session session = NULL;
Transaction tran = null;
try {
Session = Hibernatesessionfactory.getsession ();
Tran = Session.begintransaction ();
Session.save (object);
Tran.commit ();
} catch (Exception e) {
Tran.rollback ();
} finally {
Session.close ();
}
}

}

Userdao Implementation class:

public class Userdaoimpl extends Basedaoimpl implements Iuserdao {

public void Save (user user) {
Super.save (user);
}

}

In this way, the database operation of the method directly write a good, unified in the Basedao inside. When you want to save the product, call the Save method inside Basedao, and replace the object parameter with the product concrete.

Delete and modify the same reason.

So, the next one is the query. Queries are relatively cumbersome.

I first query a single object as an example, query a record based on ID, and return a result.

The query has several problems: 1, the parameters are different types, 2, the number of parameters is unknown; 3, the type of the returned result is unknown.

Because the type of the returned result is unknown, the object to be queried is not known, so the query can only be passed in as a parameter, because of the different types of parameters, so do not call Query.setinteger, query.setstring and other methods. Here, there are two methods, one is to pass the parameter list in a map, the parameter list in the map must be a simple object before the line, call the Query.setparameter method. The other is to enclose the parameter in an entity class wrapper, and the entity as a parameter can call the Query.setproperty method. As for the type of return result, I think it is expected that you would expect to receive it with object. This is OK, but I personally feel bad, I suggest you use the model to receive.

Here's some code:

Basedao Interface:

Public interface Ibasedao {

void Save (Object object);

void Delete (Object object);

void update (Object object);

/**
* Query results return a list collection
* @param params Map parameter list
* @return T is received with list when returning results
*/
Public <T> T queryForList (String hql, map<string, object> params);

/**
* Query results return a list collection
* @param params Map parameter list
* @return T is received with list when returning results
*/
Public <T> T queryForList (String hql, Object Parambean);

/**
* Query results return a single object
* @param hql
* @return T is received with the entity class when the result is returned
*/
Public <T> T queryForObject (String hql, map<string, object> params);

}

Basedao Implementation class:

Package Dao.impl;

Import Java.util.Map;
Import Java.util.Map.Entry;

Import Org.hibernate.Query;
Import org.hibernate.Session;
Import org.hibernate.Transaction;

Import util. Hibernatesessionfactory;
Import DAO. Ibasedao;

public class Basedaoimpl implements Ibasedao {

public void Save (object object) {
Session session = NULL;
Transaction tran = null;
try {
Session = Hibernatesessionfactory.getsession ();
Tran = Session.begintransaction ();
Session.save (object);
Tran.commit ();
} catch (Exception e) {
Tran.rollback ();
} finally {
Session.close ();
}
}

public void Delete (Object object) {
Session session = NULL;
Transaction tran = null;
try {
Session = Hibernatesessionfactory.getsession ();
Tran = Session.begintransaction ();
Session.delete (object);
Tran.commit ();
} catch (Exception e) {
Tran.rollback ();
} finally {
Session.close ();
}
}

Public void Update (Object object) {
Session session = NULL;
Transaction tran = null;
try {
session = Hibernatesessionfactory.getsession ();
Tran = Session.begintransaction ();
Session.update (object);
Tran.commit ();
} catch (Exception e) {
Tran.rollback ();
} finally {
Session.close ();
}
}

/**
* Parameter name must be consistent with object property name
*
* @param params
* MAP parameter list
* @return List
*/
@SuppressWarnings ("UNC Hecked ")
Public <T> T queryforlist (String hql, map<string, object> params) {
Session session = Null; Transaction tran = null;
Query query = NULL;
T result = null;
try {
session = Hibernatesessionfactory.getsession ();
Tran = Session.begintransaction ();
Query = Session . CreateQuery (HQL);
if (params! = null) {
for (entry<string, object> entry:params.entrySet ()) {
Query.setparameter (Entry. GetKey (), Entry.getvalue ());
}
}
result = (T) query.list ();
Tran.commit ();
} catch (Exception e) {
Tran.rollback ();
} FINA lly {
Session.close ();
}
Return (T) result;
}

/**
* Parameter name must match object property name
*
* @param parambean
* Parameter Object
*/
@SuppressWarnings ("unchecked")
Public <T> T queryForList (String hql, Object Parambean) {
Session session = NULL;
Transaction tran = null;
Query query = NULL;
T result = null;
try {
session = Hibernatesessionfactory.getsession ();
Tran = Session.begintransaction ();
Query = Session . CreateQuery (HQL);
Query.setproperties (Parambean);
result = (T) query.list ();
Tran.commit ();
} catch (Exception e) {
Tran.rollback ();
} finally {
Session.close ();
}
Return (T) result;
}

/**
* Parameter names must be consistent with object property names
*
* @param params
* Query results return a single object
* @return T Returns an entity class object
*/
@SuppressWarnings ("Unchecked")
Public <T> T queryForObject (String hql, map<string, object> params) {
Session session = NULL;
Transaction tran = null;
query query = NULL;
T result = null;
try {
Session = Hibernatesessionfactory.getsession ();
Tran = Session.begintransaction ();
query = Session.createquery (HQL);
For (entry<string, object> entry:params.entrySet ()) {
Query.setparameter (Entry.getkey (), Entry.getvalue ());
}
result = (T) query.uniqueresult ();
Tran.commit ();
} catch (Exception e) {
Tran.rollback ();
} finally {
Session.close ();
}
return (T) result;
}

}

Orderdao Interface:

Public interface Iorderdao {

void Save (order order);

void Delete (order order);

void update (order order);

Order Queryorderbyid (int order_id);

List<order> queryorderbyuser (user user);

}

Orderdao Implementation class:

public class Orderdaoimpl extends Basedaoimpl implements Iorderdao {

public void Save (order order) {
Super.save (order);
}

public void Delete (order order) {
Super.delete (order);
}

public void Update (order order) {
Super.update (order);
}

/**
* Search by ID <br>
* Map as a parameter transmission carrier
* @param order_id
*/
Public Order Queryorderbyid (int order_id) {
String hql = "From order order where order.order_id =: order_id";
map<string, object> params = new hashmap<string, object> (1);
Params.put ("order_id", order_id);
Return Super.queryforobject (HQL, params);
}

/**
* Order <br> According to the user's enquiry
* Transfer the entity as a parameter carrier
*/
Public list<order> queryorderbyuser (user user) {
String hql = "From order order where order.user.user_id =: user_id";
Return Super.queryforlist (hql, user);
}

}

Multi-layered optimization problem of hibernate

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.