azizkhani.net

I know that I know nothing

Hibernate 5 : generator class=“sequence” not working

clock March 3, 2016 18:54 by author Administrator

after upgrade hibernate 4 to 5 sequence not working and hibernate get next val from hibernate_sequence  but 

I solved it by re-configuring mapping in the HBM file from:

<generator class="sequence">

           <param name="sequence">PRODUCT_ID_SEQ</param>

</generator>

to:

<generator class="org.hibernate.id.enhanced.SequenceStyleGenerator">

          <param name="prefer_sequence_per_entity">true</param>

          <param name="optimizer">none</param>

          <param name="increment_size">1</param>

          <param name="sequence_name">PRODUCT_ID_SEQ</param>

</generator> 

ref:http://stackoverflow.com/questions/2155376/how-to-use-existing-oracle-sequence-to-generate-id-in-hibernate


The value of attribute "formula" must not contain the '<' character.

clock May 8, 2015 12:43 by author Administrator

hibernate formula dosenot allow user < in select for example i use this formula and get this exception

  <property name="debitPrice"  not-null="true"   formula="(  select nvl(sum(d.cost_price),0) from ihs_flat_cost_assign d where d.flat_id=Id  and d.cost_price <=0   )  "   />

 

and i change that to this

        <property name="debitPrice"  not-null="true"   formula="(  select nvl(sum(d.cost_price),0) from ihs_flat_cost_assign d where d.flat_id=Id  and 0>=d.cost_price    )  "   />

and problem solve

crazyyyyy bug i dont know whyyyyy



Hibernate exception _$$_javassist_0 cannot be cast to javassist.util.proxy.Proxy

clock December 23, 2014 22:18 by author Administrator

hibernate 4.3.7 using javasssist new version and oracle weblogic older than that version for solve this problem will add this configuration to weblogic.xml

<wls:container-descriptor>
        <wls:prefer-application-packages>
            <wls:package-name>javassist</wls:package-name>
        </wls:prefer-application-packages>
    </wls:container-descriptor>



Hibernate: Version-Based Optimistic Concurrency Control

clock November 11, 2014 22:17 by author Administrator

Optimistic locking discards all incoming changes that are relative to an older entity version. But everything has a cost and optimistic locking makes no difference.

The optimistic concurrency control mechanism takes an all-or-nothing approach even for non-overlapping changes. If two concurrent transactions are changing distinct entity property subsets then there’s no risk of losing updates.

Two concurrent updates, starting from the same entity version are always going to collide. It’s only the first update that’s going to succeed, the second one failing with an optimistic locking exception. This strict policy acts as if all changes are overlapping. For highly concurrent write scenarios, this single-version check strategy can lead to a large number of roll-backed updates.

optimisticlockingoneproductentityoneversion

 

http://a3ab771892fd198a96736e50.javacodegeeks.netdna-cdn.com/wp-content/uploads/2014/11/optimisticlockingonerootentityoneversion1.png



Bulk fetching with Hibernate

clock March 20, 2013 13:40 by author Administrator


If you need to process large database result sets from Java you can opt for JDBC to give you the low level control required. On the other hand if you are already using an ORM in your application falling back to JDBC might imply some extra pain. You would be losing features such as optimistic locking, caching, automatic fetching when navigating the domain model and so forth. Fortunately most ORMs, like Hibernate, have some options to help you with that. While these techniques are not new, there are a couple of possibilities to choose from.

http://koenserneels.blogspot.be/2013/03/bulk-fetching-with-hibernate.html



ROW LEVEL SECURITY (BEST SOLUTION?)

clock October 25, 2012 19:21 by author Administrator

 

HELP ME
here might be special rows in a database which should only visible and accessible by users with special privileges. To avoid unnecessary round-trips, we currently modify the SQL queries to join with our authorization data to get only the visible rows for the current user.

But this concepts doesn't feel 'right' to me, because we mix business code with security related code which should be orthogonal and independent from each other.

 

  • What solutions are available/possible?
  • How do you implement row-level security (especially in combination with hibernate)?

The idea is that you can implement row level functionality in two ways: directly setting restrictions in your repository or binding the restrictions via AOP. The latter is preferred because security layer should be separated from business logic (orthogonal concerns).

 

In Hibernate you can use the concept of filters which are applied transparently and repository doesn't know about them. You can add such filters via AOP. The other way is intercepting session.createCriteria() and adding Restrictions to the Criteria transparently using AOP.

 



Spring and hibernate 4 integration

clock October 25, 2012 18:29 by author Administrator

add this dependancy

 

    <!-- Hibernate framework -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.1.4.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0.2</version>
        </dependency>
        <!-- end hibernate -->

 

and then change spring configuration like this

 



    <tx:annotation-driven transaction-manager="hibernateTransactionManager" />
    <bean id="dataSource"  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${hibernate.connection.driver_class}" />
        <property name="url" value="${hibernate.connection.url}" />
        <property name="username" value="${hibernate.connection.username}" />
        <property name="password" value="${hibernate.connection.password}" />
    </bean>
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mappingLocations">
            <list>
                <value>/WEB-INF/classes/hibernate/**/*.hbm.xml</value>
            </list>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.connection.driver_class"> ${hibernate.connection.driver_class}</prop>
                <prop key="hibernate.connection.url"> ${hibernate.connection.url}</prop>
                <prop key="hibernate.connection.username"> ${hibernate.connection.username}</prop>
                <prop key="hibernate.connection.password"> ${hibernate.connection.password}</prop>
                <!-- <prop key="hibernate.connection.internal_logon"> ${hibernate.connection.internal_logon}</prop> -->
                <prop key="hibernate.dialect"> ${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql"> ${hibernate.show_sql}</prop>
                <prop key="hibernate.hbm2ddl.auto"> ${hibernate.hbm2ddl_auto}</prop>
                <!-- <prop key="hibernate.default_schema"> ${hibernate.default_schema}</prop> -->
            </props>
        </property>
    </bean>

    <bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

 

and now

 

package org.azizkhani.dao;

import java.util.List;

import org.azizkhani.core.QueryResult;

public interface IGenericRepository<T> {
    public List<T> getAll();
    public List<T> getAll(String where, String order, int pageNumber,int pageSize);
    public QueryResult<T> getAllGrid(String where, String order, int pageNumber,int pageSize);
    public T loadByEntityId(int entityId);
    public T single(String where);
    public void add(T entity);
    public void delete(T entity);
    public void deleteByEntityId(int entityId);
    public void update(T entity);
    public int count();
}

 

implementation

 

package org.azizkhani.dao.impl.hibernate;

import java.util.List;

import org.azizkhani.common.utility.HQLUtility;
import org.azizkhani.core.QueryResult;
import org.azizkhani.dao.IGenericRepository;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public abstract class GenericRepository<T>  implements IGenericRepository<T> {
    protected Class<T> domainClass = getDomainClass();

    protected abstract Class<T> getDomainClass();
   
    @Autowired
    private SessionFactory sessionFactory;
   

    @Override
    public List<T> getAll() {
        Criteria criteria = getSession().createCriteria(domainClass.getName());
        return criteria.list();
    }

    public Session getSession() {
        try {
            return sessionFactory.getCurrentSession();
        } catch (Exception e) {
            System.out.println(e.getMessage().toString());
        }
        return sessionFactory.openSession();
    }

    public QueryResult<T> getAllGrid(String where, String order, int pageNumber, int pageSize) {
        Session session = getSession();
        StringBuffer jql = new StringBuffer("from " + domainClass.getName()
                + " e ");
        HQLUtility.toHQL(jql, where, order);
        Query query = session.createQuery(jql.toString());
        if (pageSize > 0)
        {
            query.setFirstResult(pageNumber * pageSize);
            query.setMaxResults(pageSize);
        }
        List<T> list = query.list();

        StringBuffer jqlCount = new StringBuffer("select count(*)  from "
                + domainClass.getName() + " e ");
        HQLUtility.toHQL(jqlCount, where, "");
        int count = ((Long) getSession().createQuery(jqlCount.toString())
                .uniqueResult()).intValue();

        return new QueryResult<T>(pageNumber, count, pageSize, list);
    }

    @Override
    public List<T> getAll(String where, String order, int pageNumber, int pageSize) {
        Session session = getSession();
        StringBuffer jql = new StringBuffer("from " + domainClass.getName()
                + " e ");
        HQLUtility.toHQL(jql, where, order);
        Query query = session.createQuery(jql.toString());
        if (pageSize > 0)
        {
            query.setFirstResult(pageNumber * pageSize);
            query.setMaxResults(pageSize);
        }
        return query.list();
    }
    @Transactional(readOnly=true)
    @Override
    public T loadByEntityId(int entityId) {
        return (T) getSession().load(domainClass, entityId);
    }

    @Override
    public T single(String where) {
        return null;
    }

    @Override
    public void add(T entity) {
        Session session = getSession();
        session.beginTransaction();
        session.save(entity);
        session.getTransaction().commit();
        session.close();
    }

    @Override
    public void delete(T entity) {
        getSession().delete(entity);
    }

    @Override
    public void deleteByEntityId(int entityId) {
        Session session = getSession();
        session.beginTransaction();
        Object obj = session.load(domainClass, entityId);
        session.delete(obj);
        session.getTransaction().commit();
        session.close();
    }

    @Override
    public void update(T entity) {
        Session session = getSession();
        session.beginTransaction();
        session.update(entity);
        session.getTransaction().commit();
        session.close();
    }

    @Override
    public int count() {
        int count = ((Long) getSession().createQuery(
                "select count(*) from " + domainClass.getName()).uniqueResult())
                .intValue();
        return count;
    }
}



 

 





setResultTransformer in hibernate

clock August 24, 2012 22:34 by author Administrator

یکی از مواردی که حتما در کار کردن با hibernate براتون پیش اومده اینه که یکquery بنویسیدکه نتیجه اون چیزی به غیر از یکی از

domain model شما باشه برای مثال استفاده از دستورات count,sum,و  در این حالت باید یک مدل جدید برای نتایج ایجاد کنید برای

مثال اگر شما بخواهید این نتایج را برگدونید باید روش زیر را انجام بدید

 
Iterator results = sess.createQuery(
        "select cat.color, min(cat.birthdate), count(cat) from Cat cat " +
        "group by cat.color")
        .list()
        .iterator();

while ( results.hasNext() ) {
    Object[] row = (Object[]) results.next();
    Color type = (Color) row[0];
    Date oldest = (Date) row[1];
    Integer count = (Integer) row[2];
    .....
}

 ولی این راه حل مشکلی که داره اینه که اولا وابسته به index نتایج هستید و کلا کار قشنگ و درستی نیست ولی حالا کد زیر را نگاه کنید

 
Query query=sess.createQuery("select cat.color, min(cat.birthdate), count(cat) from Cat cat
group by cat.color").setResultTransformer(Transformers.aliasToBean(YourObject.class));
List<YourObject> lst=query.list();
 


Hibernate NamingStrategy

clock August 24, 2012 22:02 by author Administrator

حتما تا حالا در مورد این قضیه فکر کردید که در هایبرنت کاش میشد یه کاری کنیم که نام گذاریهای تولید شده برای

table,constraint,..

به صورت اتوماتیک و طبق استاندارد مشخصی که خودمون تعریف میکنیم باشه برای مثال اول نام جدول

tbl

باشه برای این کار قابلیتی وجود داره که میتون این کار رو انجام بده

Hibernate NamingStrategy

کد زیر یک نمونه برای اینکار است که با توجه به محدودیتهای پایگاه داده اراکل(تعداد کاراکتر ۳۰ )برای نام گذاری است پیاده شده

package org.common.utility;

import org.hibernate.cfg.DefaultComponentSafeNamingStrategy;

import java.util.StringTokenizer;

public class OracleNamingStrategy extends DefaultComponentSafeNamingStrategy {
    private static final long serialVersionUID = -3020615242092992933L;

    protected static String addUnderscores(String name) {
        if (name == null)
            return null;
        StringBuffer buf = new StringBuffer(name.replace('.', '_'));
        for (int i = 1; i < buf.length() - 1; i++) {
            if ((isLowerToUpper(buf, i)) || (isMultipleUpperToLower(buf, i))

            ) {
                buf.insert(i++, '_');
            }
        }
        return buf.toString().toLowerCase();
    }

    private static boolean isMultipleUpperToLower(StringBuffer buf, int i) {
        return i > 1 && Character.isUpperCase(buf.charAt(i - 1))
                && Character.isUpperCase(buf.charAt(i - 2))
                && Character.isLowerCase(buf.charAt(i));
    }

    private static boolean isLowerToUpper(StringBuffer buf, int i) {
        return Character.isLowerCase(buf.charAt(i - 1))
                && Character.isUpperCase(buf.charAt(i));
    }

    @Override
    public String collectionTableName(String ownerEntity,
            String ownerEntityTable, String associatedEntity,
            String associatedEntityTable, String propertyName) {
        return abbreviateName(super.collectionTableName(
                addUnderscores(ownerEntity), addUnderscores(ownerEntityTable),
                addUnderscores(associatedEntity),
                addUnderscores(associatedEntityTable),
                addUnderscores(propertyName)));
    }

    @Override
    public String foreignKeyColumnName(String propertyName,
            String propertyEntityName, String propertyTableName,
            String referencedColumnName) {
        return abbreviateName(super.foreignKeyColumnName(
                addUnderscores(propertyName),
                addUnderscores(propertyEntityName),
                addUnderscores(propertyTableName),
                addUnderscores(referencedColumnName)));
    }

    @Override
    public String logicalCollectionColumnName(String columnName,
            String propertyName, String referencedColumn) {
        return abbreviateName(super.logicalCollectionColumnName(
                addUnderscores(columnName), addUnderscores(propertyName),
                addUnderscores(referencedColumn)));
    }

    @Override
    public String logicalCollectionTableName(String tableName,
            String ownerEntityTable, String associatedEntityTable,
            String propertyName) {
        return abbreviateName(super.logicalCollectionTableName(
                addUnderscores(tableName), addUnderscores(ownerEntityTable),
                addUnderscores(associatedEntityTable),
                addUnderscores(propertyName)));
    }

    @Override
    public String logicalColumnName(String columnName, String propertyName) {
        return abbreviateName(super.logicalColumnName(
                addUnderscores(columnName), addUnderscores(propertyName)));
    }

    @Override
    public String propertyToColumnName(String propertyName) {
        return abbreviateName(super
                .propertyToColumnName(addUnderscores(propertyName)));
    }

    private static final int MAX_LENGTH = 30;

    public static String abbreviateName(String someName) {
        if (someName.length() <= MAX_LENGTH)
            return someName;

        String[] tokens = splitName(someName);
        shortenName(someName, tokens);

        return assembleResults(tokens);
    }

    private static String[] splitName(String someName) {
        StringTokenizer toki = new StringTokenizer(someName, "_");
        String[] tokens = new String[toki.countTokens()];
        int i = 0;
        while (toki.hasMoreTokens()) {
            tokens[i] = toki.nextToken();
            i++;
        }
        return tokens;
    }

    private static void shortenName(String someName, String[] tokens) {
        int currentLength = someName.length();
        while (currentLength > MAX_LENGTH) {
            int tokenIndex = getIndexOfLongest(tokens);
            String oldToken = tokens[tokenIndex];
            tokens[tokenIndex] = abbreviate(oldToken);
            currentLength -= oldToken.length() - tokens[tokenIndex].length();
        }
    }

    private static String assembleResults(String[] tokens) {
        StringBuilder result = new StringBuilder(tokens[0]);
        for (int j = 1; j < tokens.length; j++) {
            result.append("_").append(tokens[j]);
        }
        return result.toString();
    }

    private static String abbreviate(String token) {
        final String VOWELS = "AEIOUaeiou";
        boolean vowelFound = false;
        for (int i = token.length() - 1; i >= 0; i--) {
            if (!vowelFound)
                vowelFound = VOWELS.contains(String.valueOf(token.charAt(i)));
            else if (!VOWELS.contains(String.valueOf(token.charAt(i))))
                return token.substring(0, i + 1);
        }
        return "";
    }

    private static int getIndexOfLongest(String[] tokens) {
        int maxLength = 0;
        int index = -1;
        for (int i = 0; i < tokens.length; i++) {
            String string = tokens[i];
            if (maxLength < string.length()) {
                maxLength = string.length();
                index = i;
            }
        }
        return index;
    }

    @Override
    public String classToTableName(String aClassName) {

        return abbreviateName(super
                .classToTableName(addUnderscores(aClassName)));
    }
}

حالا باید این را به تنظیمات هایبرنت اضافه کنیم

<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mappingLocations">
			<list>
				<value>/WEB-INF/classes/hibernate/**/*.hbm.xml</value>
			</list>
		</property>
		<property name="namingStrategy" ref="namingStrategy" />
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.connection.driver_class"> ${hibernate.connection.driver_class}</prop>
				<prop key="hibernate.connection.url"> ${hibernate.connection.url}</prop>
				<prop key="hibernate.connection.username"> ${hibernate.connection.username}</prop>
				<prop key="hibernate.connection.password"> ${hibernate.connection.password}</prop>
				<prop key="hibernate.dialect"> ${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql"> ${hibernate.show_sql}</prop>
				<prop key="hibernate.hbm2ddl.auto"> ${hibernate.hbm2ddl_auto}</prop>
			</props>
		</property>
	</bean>
	<bean id="namingStrategy" class="org.common.utility.OracleNamingSthrategy"/>


Hibernate Inheritance

clock March 9, 2012 21:21 by author Administrator

 

 



About the author

 Welcome to this web site . This page has two purposes: Sharing information about my professional life such as articles, presentations, etc.
This website is also a place where I would like to share content I enjoy with the rest of the world. Feel free to take a look around, read my blog


Java,J2EE,Spring Framework,JQuery,

Hibernate,NoSql,Cloud,SOA,Rest WebService and Web Stack tech...

RecentPosts

Month List

Sign In