spring 2.5.6 and hibernate3.2.2 Integration (2)

Write an article on how to use the spring annotations, this one recorded with a simple click, and hibernate.

1. Using a variety of mysql command line client or directly perform the following script:

create database if not exists `test`;

USE `test`;

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. Since it is of course, require Model of ORM

package com.isa.demo2.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.apache.commons.lang.builder.ToStringBuilder;


@Entity
@Table(name = "user")
public class User implements Serializable {
        /**
         * 
         */
        private static final long serialVersionUID = -9029863029696113906L;
        private long id;
        private String name;
        
        @Id
        @Column(name = "ID", unique = true, nullable = false, scale = 0)
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        public long getId() {
                return id;
        }
        public void setId(long id) {
                this.id = id;
        }
        
        @Column(name = "NAME", unique = true, nullable = false)
        public String getName() {
                return name;
        }
        public void setName(String name) {
                this.name = name;
        }
        @Override
        public String toString() {
                return ToStringBuilder.reflectionToString(this);
        }
        
}

3. With regard to the issue was necessary dao layer to see everyone's habits, as a demo, can be simple and straightforward. Here's a project using the previous structure.

package com.isa.demo2.service;

import java.util.List;

import com.isa.demo2.domain.User;

public interface UserService {
        List<User> getAllUsers();
        User getUserById(long id);
}

4. Interface implementation class

package com.isa.demo2.service;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.isa.demo2.domain.User;

public class UserServiceImpl implements UserService {

        private SessionFactory sessionFactory;
                
        public SessionFactory getSessionFactory() {
                return sessionFactory;
        }

        public void setSessionFactory(SessionFactory sessionFactory) {
                this.sessionFactory = sessionFactory;
        }
        
        @Override
        public List<User> getAllUsers() {
                Session session = sessionFactory.getCurrentSession();
                String hql = "from User";
                List<User> list = session.createQuery(hql).list();
                return list;
        }

        @Override
        public User getUserById(long id) {
                Session session = sessionFactory.getCurrentSession();
                User user = (User) session.get(User.class, id);
                return user;
        }

}

5. Configuration file applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
           default-autowire="byName" default-lazy-init="true">
        
        <!--  Support  @Transactional  Mark  -->
        <tx:annotation-driven/>

        <!--  Support  @AspectJ  Mark  -->
        <aop:aspectj-autoproxy/>
        
        <aop:config>
                <aop:pointcut expression="execution(* com.isa.demo2.service.*.*(..))"/>
                <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation"/>
        </aop:config>


        <tx:advice transaction-manager="transactionManager">
                <tx:attributes>
                        <tx:method name="get*" read-only="true"/>
                        <tx:method name="*"/>
                </tx:attributes>
        </tx:advice>

        <bean></bean>

</beans>

The second configuration file applicationContext-hibernate.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans default-autowire="byName" default-lazy-init="true">
        
        <!--  The data source definition  , Use dbcp connection pooling  -->
        <!--  The data source configuration  , Use the apply DBCP within the database connection pool  -->
        <bean destroy-method="close">
                <!-- Connection Info -->
                <property name="driverClassName" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost/test?useUnicode=true&amp;characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="123456" />

                <!-- Connection Pooling Info -->
                <property name="initialSize" value="5" />
                <property name="maxActive" value="100" />
                <property name="maxIdle" value="30" />
                <property name="maxWait" value="1000" />
                <property name="poolPreparedStatements" value="false" />
                <property name="defaultAutoCommit" value="false" />
        </bean>

        <!--Hibernate SessionFatory-->
        <bean>
                <property name="dataSource" ref="dataSource"/>
                <property name="annotatedClasses">
                        <list>
                                <value>com.isa.demo2.domain.User</value>
                        </list>
                </property>
                <property name="hibernateProperties">
                        <props>
                                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                                <prop key="hibernate.show_sql">false</prop>
                                <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
                                <prop key="hibernate.cache.use_query_cache">true</prop>
                        </props>
                </property>
        </bean>

        <!--Hibernate TransactionManager-->
        <bean>
                <property name="sessionFactory" ref="sessionFactory"/>
        </bean>
</beans>

6. A simple test class

package com.isa.demo2.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.isa.demo2.service.UserService;

public class Demo2Test {

        /**
         * @param args
         */
        public static void main(String[] args) {
                ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "demo2/*.xml" });
                UserService service = (UserService)context.getBean("userService");
                System.out.println(service.getUserById(1L).toString());
        }
}

7. Note: This demo comes from the time I have just graduated to do a project, which is the first contact with spring and hibernate, the structure of that project looks pretty weird, C # + hessian + hibernate + spring + Oracle, Oh, why is a C # do? But also a client program, see the hessian will know. Some technology is not to forget, and in this paragraph do not use hibernate and spring time to update and add a lot of features, and now can be considered to re-look at the times. Another nagging about, technology, and language is endless, but the learning skills and experience is required summarized in order to progress.
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of spring 2.5.6 and hibernate3.2.2 Integration (2)

  • Servlet brief introduction

    Servlet brief introduction: Servlet is a small application server Are used to complete the B / S architecture, the client requests the response to treatment Platform independence, performance, able to run thread Servlet API for Servlet provides the s ...

  • First Hibernate Example

    Curd a simple example. Source does not contain the dependent libraries, or playing too much of the package. PO object Note: One must have the default constructor 2 non-final modified. Otherwise useless lazy loading. UserDAOImpl category code, and oth ...

  • Hibernate annotation using notebook

    These are the basic common comment, the following are examples to illustrate TU is a two-way as long as if the increase in Largess

  • Struts2 + hibernate + spring problem user log in

    dao layer services layer action jsp <tr> <td align="center"> <b> user name: </ b> </ td> <td> <s: textfield name = "czyNumber" cssClass = "textstyle" theme = "simple" size = &q

  • The level Hibernate cache

    Hibernate cache level: (1) a cache is very short and the session life cycle consistent, also known as session-level cache-level cache or transaction-level cache (2) Ways of Supporting level cache: get (); load (); iterator (); only entity object cach ...

Leave a Reply

Recent
Recent Entries
Tag Cloud
Random Entries