working on it ...

Filters

Explore Public Snippets

Sort by

Found 377 snippets matching: hibernate

    public by AnghelLeonard  212358  3  5  0

    Hibernate JPA - programmatically set the transaction isolation level for the current connection

    Hibernate JPA - programmatically set the transaction isolation level for the current connection
    entityManager = entityManagerFactory.createEntityManager();
                Session session = (Session) entityManager.getDelegate();            
                session.doWork((Connection connection) -> {
                    connection.setTransactionIsolation(
                            Connection.TRANSACTION_READ_COMMITTED);
                });

    public by xiongtec  3159  1  6  0

    @transactional rollback

    You shouldn't call Rollback programmatically. The best way, as recommended by the docs, is to use declarative approach. To do so, you need to annotate which exceptions will trigger a Rollback.
    
    In your case, something like this
    
    @Transactional(rollbackFor={MyException.class, AnotherException.class})
    public SomeResult doSomething(){
       ...
    }
    Take a look at the @Transaction API and the docs about rolling back a transaction.
    
    If, despite the docs recommendation, you want to make a programmatic rollback, then you need to call it from TransactionAspectSupport as already suggested. This is from the docs:
    
    public void resolvePosition() {
      try {
        // some business logic...
      } catch (NoProductInStockException ex) {
        // trigger rollback programmatically
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      }
    }
    There may be a architecture mistake though. If your method fails and you need to throw an exception, you shouldn't expect it to return anything. Maybe you're giving too much responsibilities to this method and should create a separated one that only model data, and throws an exception if something goes wrong, rolling back the transaction. Anyway, read the docs.

    public by AnghelLeonard  1755  0  5  0

    Execute a Hibernate SQLQuery via EntityManager

    Execute a Hibernate SQLQuery via EntityManager
    List results = ((Session)this.entityManager.getDelegate()).createSQLQuery(
                    "SELECT a.name AS namep, b.name AS names, c.name AS namet"
                            + " FROM secondarycategory b"
                            + " INNER JOIN topcategory a ON a.id=b.top_id"
                            + " INNER JOIN thirdcategory c ON b.id=c.secondary_id").list();

    public by AnghelLeonard  1594  0  3  0

    Hibernate JPA - Get the transaction isolation level in a readable fashion

    Hibernate JPA - Get the transaction isolation level in a readable fashion
    Session session = (Session) entityManager.getDelegate();
                session.doWork((Connection connection) -> {
                    String result;
                    int til = connection.getTransactionIsolation();
                    switch (til) {
                        case Connection.TRANSACTION_READ_COMMITTED:
                            result = "TRANSACTION_READ_COMMITTED";
                            break;
                        case Connection.TRANSACTION_READ_UNCOMMITTED:
                            result = "TRANSACTION_READ_UNCOMMITTED";
                            break;
                        case Connection.TRANSACTION_REPEATABLE_READ:
                            result = "TRANSACTION_REPEATABLE_READ";
                            break;
                        case Connection.TRANSACTION_SERIALIZABLE:
                            result = "TRANSACTION_SERIALIZABLE";
                            break;
                        default:
                            result = "TRANSACTION_NONE";
                            break;
                    }
                    LOG.info("Current transaction isolation level: " + result);
                });

    public by AnghelLeonard  1287  0  5  0

    Hibernare evict second level cache

    Hibernare evict second level cache
    Session session = (Session) entityManager.getDelegate();
    session.getSessionFactory().getCache().evictAllRegions();

    external by Ð?ng Minh Dung  411  2  3  0

    [Java][JPA][Hibernate] UUID & Hibernate

    [Java][JPA][Hibernate] UUID & Hibernate: Model.java
    @Entity
    public class Employee extends AbstractBaseEntity {
      //  Approach 1:
      //  @Id
      //  public String id;
    
      //  Approach 2:
      @Id
      // default column type is byte array
      @Type(type = "org.hibernate.type.PostgresUUIDType") // or type = "pg-uuid"
      @GeneratedValue(generator = "uuid")
      @GenericGenerator(
              name = "uuid",
              strategy = "org.hibernate.id.UUIDGenerator",
              parameters = {
                      @Parameter(
                              name = "uuid_gen_strategy_class",
                              value = "org.hibernate.id.uuid.CustomVersionOneStrategy"
                      )
              }
      )
      public UUID id;
      
      public AbstractBaseEntity() {
        //  Approach 1:
        //  this.id = UUID.randomUUID().toString();
      }
    }
    
    

    external by MangoLiu  410  0  3  0

    Hibernate persistence operation (Hibernate 持久化操作的一般步骤)

    Hibernate persistence operation (Hibernate 持久化操作的一般步骤) : NewsManager.java
    public class NewsManager{
    	public static void main(String[] args) throws Exception{
    		//实例化Configuration
    		Configuration conf = new Configuration().configure();
    		//创建SessionFactory
    		SessionFactory sf = conf.buildSessionFactory();
    		//创建Session
    		Session session = sf.openSession();
    		//开始事务
    		Tracsaction tx = sess.beginTransaction();
    
    		//创建消息实体
    		News n = new News();
    		n.setTitle("Mango");
    		n.setContent("Liu");
    
    		//保存消息
    		session.save(n);
    		//提交事务
    		tx.commit();
    		//关闭session
    		session.close();
    		sf.close();
    	}
    }
    
    

    external by jianshe  269  0  3  0

    spring,hibernate,struts中基于注解的整合。

    spring,hibernate,struts中基于注解的整合。: web.xml
    XML
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" 
    	xmlns="http://java.sun.com/xml/ns/javaee" 
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    	
    	
      <!-- OpenSessionInView-->
      <filter>
      	<filter-name>opensessioninview</filter-name>
      	<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
      </filter>
      <filter-mapping>
      	<filter-name>opensessioninview</filter-name>
      	<url-pattern>/*</url-pattern>
      </filter-mapping>
    	
      <!-- Struts2的控制器 -->
      <filter>
      	<filter-name>struts2</filter-name>
      	<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
      </filter>
      
      <filter-mapping>
      	<filter-name>struts2</filter-name>
      	<url-pattern>/*</url-pattern>
      </filter-mapping>
      
      <!-- Spring监听器 --><!--实现让spring容器启动时来加载配置文件-->
      <context-param>
      	<param-name>contextConfigLocation</param-name>
      	<param-value>classpath:applicationContext*.xml</param-value>
      </context-param>
      <listener>
    	<listener-class>
    		org.springframework.web.context.ContextLoaderListener
    	</listener-class>
      </listener>
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    	
    </web-app>
    
    
    

    external by MangoLiu  266  0  3  0

    Hibernate mapping file (Hibernate 映射文件:classname.hbm.xml)

    Hibernate mapping file (Hibernate 映射文件:classname.hbm.xml): classname.hbm.xml
    XML
    <?xml version="1.0" encoding='UTF-8'?>
    <!DOCTYPE hibernate-mapping PUBLIC
         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
         "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
    <!-- 以上4行,所有的配置xml文件都一样。 -->
    <hibernate-mapping package="包名"> 
        <class name="类名" table="表名"> <!-- 每个class元素对应一个持久化对象,即一个数据表。 -->
                  <!-- id元素定义持久化类的标识属性。 -->
                 <id name="类中的字段名" column="对应表中字段" type="类型 ">
                      <generator class="identity"/><!-- 主键生成策略 -->
                 </id>
                 <!-- property元素定义常规属性。 -->
                 < property name = "类中的其他字段"/>
                 < property name = "类中的其他字段"/><!-- 可以有很多。 -->
        </class>
    </hibernate-mapping>
    
    

    external by Daniel Hanke  172  0  2  0

    Hibernate DetachedCriteria using subqueries exists clause, while eager fetching the lazy collection that is in the exists clause, and running via Spring HibernateTemplate findByCriteria, and limit results to max of 2000.

    Hibernate DetachedCriteria using subqueries exists clause, while eager fetching the lazy collection that is in the exists clause, and running via Spring HibernateTemplate findByCriteria, and limit results to max of 2000.: gistfile1.java
    /*
     * HQL would look something like this:
     *
     * from Person p join fetch p.addresses address
     * where exists (
     *   from Address addr left join addr.state st
     *   where addr.personId = p.id
     *   and st.abbreviation = :abbreviation
     * )
     */
    
    DetachedCriteria criteria = DetachedCriteria.forClass(Person.class, "p");
    
    //addresses is set to lazy=true in hbm.xml file, but we want to pull back all
    //addresses for a Person, so we must make it eager with JOIN
    criteria.setFetchMode("addresses", FetchMode.JOIN);
    
    DetachedCriteria addressCriteria = DetachedCriteria.forClass(Address.class, "addr");
    addressCriteria.createAlias("state", "st");
    addressCriteria.add(Restrictions.eq("st.abbreviation", abbreviation));
    addressCriteria.add(Restrictions.eqProperty("addr.personId", "p.id"));
    
    //Finds all Persons that have an Address with state abbreviation of :abbreviation
    criteria.add(Subqueries.exists(addressCriteria.setProjection(Projections.property("addr.id"))));
    
    //Limit results to first 2000 Persons that have an address matching the given state abbreviation
    List<Person> results = getHibernateTemplate().findByCriteria(criteria, 0, 2000);
    
    
    
    /**
     * A second option can be used
     * if addresses is set as lazy="false" and fetch="subselect" in hbm.xml
     * (also use this if the previous JOIN method causes duplicate rows)
     */
    DetachedCriteria criteria = DetachedCriteria.forClass(Person.class, "p");
    
    //To pull back ALL addresses use FULL_JOIN. To only pull back matching addresses use LEFT_JOIN
    int joinType = showAllAddresses ? CriteriaSpecification.FULL_JOIN : CriteriaSpecification.LEFT_JOIN;
    criteria.createAlias("addresses", "addr", joinType);
    
    criteria.createAlias("addr.state", "st");
    criteria.add(Restrictions.eq("st.abbreviation", abbreviation));
    
    
    
    • Public Snippets
    • Channels Snippets