"Java EE Spring" 28, BA Sports Network-integrated HIBERNATE4+SPRING4 (3) Use annotations

Source: Internet
Author: User
Tags connection pooling hosting

BA Sport Network-integrated HIBERNATE4+SPRING4 (3) using annotations

1. Project diagram

2, first we introduce the corresponding jar package

The benefit of using annotations goes without saying, we don't have to build tables in the database, we can rely on JPA or hibernate to help us build a table.

3. We configure the corresponding entity objects in the database

Producttype.java

/** * Features: This is the product category * File: Producttype.java * Time: May 12, 2015 10:16:21 * cutter_point */package com.cutter_point.bean.product; Import Javax.persistence.column;import Javax.persistence.entity;import Javax.persistence.generatedvalue;import  Javax.persistence.generationtype;import Javax.persistence.id;import Javax.persistence.SequenceGenerator; @Entity @sequencegenerator (name= "Seq_1", sequencename= "Seq_1", allocationsize=1,initialvalue=1) public class    producttype{/** type ID **/privateinteger typeid;    Privatestring name;    Category name Privatestring Note; Note, used for Baidu search Privateboolean visible = true; is visible Publicproducttype () {} @Column (Length=36,nullable=false) publicstring GetName () {R    Eturnname;    } publicvoid setName (String name) {this.name= name;    } @Column (length=200) publicstring getnote () {returnnote;    } publicvoid Setnote (String Note) {this.note= Note; } @Column (Nullable=false) PublicboolEan isVisible () {returnvisible;    } publicvoid setvisible (Boolean visible) {this.visible= visible;    } @Id @GeneratedValue (strategy=generationtype.sequence,generator= "seq_1")//self-growth Publicinteger GetTypeId ()    {Returntypeid;    } publicvoid Settypeid (Integer typeid) {this.typeid= typeid; }}


We don't have to configure the XML file here.

4, we configure the spring configuration file Beans.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:context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi: Schemalocation= "http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/ Spring-beans-4.1.xsd Http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context /spring-context-4.1.xsd http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/ Spring-aop-4.1.xsd http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/ Spring-tx-4.1.xsd "> <!--scan classes with spring special mechanism, which is to add all the classes under these packages to spring for management--<context:component-scan BAS E-package= "Com.cutter_point"/> <!--Property Walker--<!--<context:property-placeholderlocation= "Classpath:jdbc.properties"/>-<!--Connection Database property configuration, destroy-method= "Close" This means that the bean's default Close method can be called when the bean is destroyed--<bean id= "myDataSource" class= " Org.apache.commons.dbcp2.BasicDataSource "destroy-method=" Close "> <property name=" driverclassname "value="        Oracle.jdbc.driver.OracleDriver "/> <property name=" url "value=" Jdbc:oracle:thin: @localhost: 1522:orcl "/>        <property name= "username" value= "xf1205020116"/> <property name= "password" value= "xf1205020116"/> <!--initial value when connection pooling starts--<property name= "InitialSize" value= "1"/> <!--connection pool maximum dbcp2 It doesn't seem to be--&.        Gt <!--<property name= "maxactive" value= "$"/>-<!--maximum idle value. After a peak time, the connection pool can slowly release a portion of the connection that has not been used, and has been reduced to Maxidle---<property name= "Maxidle" value= "2"/> <!--minimum idle value. When the number of idle connections is less than the threshold, the connection pool will pre-apply for some connections to avoid peaks Late request-<property name= "Minidle" value= "1"/> </beaN> <!--hibernate two cache configuration--<bean id= "sessionfactory" class= "Org.springframework.orm.hibernate4.LocalS Essionfactorybean "> <!--configuration elided for brevity and <property name=" DataSource "ref=" Mydat Asource "/> <!--<propertyname=" mappingresources "> <list> mapping File <val Ue>com/cutter_point/bean/product/producttype.hbm.xml</value> </list> </property>--&        Gt <property name= "Hibernateproperties" > <!--to configure hibernate properties--<value> hi Bernate.dialect=org.hibernate.dialect.oracledialect Hibernate.hbm2ddl.auto=update <!--other values create, creat                E-drop, update, validate none--> hibernate.show_sql=true hibernate.format_sql=true <!--turn on the level two cache function-hibernate.cache.use_second_level_cache= true Hibernate.cache. Use_query_cache= false hibernate.cache.region.factory_class= Org.hibernate.cache.ehcache.EhCacheRegionFactory <!--Hibernate3 's level two cache configuration-<!--<propertyname= "Hibernate.cache.provider_class" >org.hib ernate.cache.ehcacheprovider</property>--> </value> </property> <propert    Y name= "Packagestoscan" value= "Com.cutter_point.bean"/> </bean> <!--transaction Manager, the bean configured above is injected into this-- <bean id= "Txmanager" class= "Org.springframework.orm.hibernate4.HibernateTransactionManager" > <property Name= "Sessionfactory" ref= "Sessionfactory"/> </bean> <!--we use annotations to enable this transaction, first we open the transaction--&LT;TX : Annotation-driven transaction-manager= "Txmanager"/> </beans>


Note that there is no need to write the corresponding XML file in our spring configuration file.

5. Next we use Spring's Ioc/di (Dependency injection) function

Here we may also come into contact with another noun called: control reversal Okay, now let's talk about what these two nouns are, what to do!

Dependency Injection: 1, who depends on who

Of course, an object relies on the Ioc/di container, which is the spring container.

2. Why you need to rely on

Objects require IOC/DI containers to provide the external resources required by the object

3, who injected into who:

It's obvious that Ioc/di's container injects an object.

4, exactly what to inject:

is the external resources needed to inject an object

Control inversion:

1. who Controls who:

Of course, it's Ioc/di's container to control the object.

2, control what:

The main control is the creation of object instances

3, why is called reversal

Reversal is relative to the positive, then what is positive? Consider the general application, what would you do if you were to use C in a? Of course, it is directly to create a C object, that is, in class A to take the initiative to obtain the required external resource C, this situation is called forward. So what's the reverse? Is that class A no longer takes the initiative to acquire C, but passively waits, waits for the Ioc/di container to get an instance of C, and then injects the reverse into Class A.

Using the legend to illustrate, first look at the time when there is no Ioc/di, the general Class A using Class C, 7 is shown:



Figure 7 General A uses C

When a Ioc/di container is available, Class A no longer takes the initiative to create C, as shown in 8:



Figure 8 Class A is no longer actively creating C


Instead of passively waiting, wait for the Ioc/di container to get an instance of C, and then inject the reverse into Class A, as shown in 9:


Figure 9 Ioc/di Container Post-Program structure

Summary:

So there's no difference between these two nouns in nature.

Dependency Injection is described from an application perspective, where dependency injection can be described as the complete point: The application relies on the container to create and inject the external resources it needs , while control inversion is described from the container's perspective, describing the complete point: the container control application, The external resources required by the container to inject the application into the application in reverse.

Content Source: http://baitai.iteye.com/blog/792980

6. Using Dependency Injection

First implement a business interface

Productservice.java
Package com.cutter_point.service.product; Import Com.cutter_point.bean.product.ProductType; publicinterfaceproductservice{     publicabstractvoid Save (ProductType type);}


Implement Interface Productservicebean.java

/** * Features: This is the product category of service class * file: Productservicebean.java * Time: May 13, 2015 15:36:06 * cutter_point */package Com.cutter_ Point.service.product.impl; Import Javax.annotation.Resource; Import Org.hibernate.sessionfactory;importorg.springframework.stereotype.service; importorg.springframework.transaction.annotation.Transactional; Importcom.cutter_point.bean.product.producttype;importcom.cutter_point.service.product.productservice; @Service          //is equivalent to defining a bean in spring, which is the way of annotating <context:component-scanbase-package= "Com.cutter_point"/>@ Transactional                 //Open Transaction public class Productservicebean implementsproductservice{         @Resource//on method execution      Dependency Injection sessionfactory         sessionfactorysessionfactory;                  @Override         publicvoid Save (producttype type)         {//               sessionfactory.getcurrentsession (). Save (type);                   Sessionfactory.getcurrentsession (). persist (type);         }}


7, Next we test the hibernate+spring annotation is configured successfully

/** * Features: This is the unit test for the product category * File: Producttest.java * Time: May 12, 2015 10:27:24 * cutter_point */package junit.test; Import Javax.sql.DataSource; Import Org.hibernate.hibernateexception;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.hibernate.cfg.configuration;import Org.junit.beforeclass;import org.junit.Test; Importorg.springframework.context.ApplicationContext; Importorg.springframework.context.support.ClassPathXmlApplicationContext; Importcom.cutter_point.bean.product.producttype;import Com.cutter_point.service.product.ProductService;    public class producttest{@BeforeClass publicstatic void Setupbeforeclass () throws Exception {} @Test   Publicvoid Test () {producttypept = new ProductType ();//new an Object Pt.settypeid (78);    Set ID Number configurationcfg = new Configuration ();    Get the configuration sessionfactorysf =cfg.configure ("/config/hibernate/hibernate.cfg.xml"). Buildsessionfactory (); Get Session Factory Sessionsession= Sf.opensession ();        Session.begintransaction ();        Session.save (PT);        Session.gettransaction (). commit ();        Session.close ();    Sf.close (); } @Test publicvoid testspring () {//test if spring works APPLICATIONCONTEXTCXT = new Classpathxmlappli        Cationcontext ("Config/spring/beans.xml");    Datasourcedatasource = (DataSource) cxt.getbean ("myDataSource"); Take out an object System.out.println (DataSource); Determine if it is empty,} @Test publicvoid Testsh () {//test if spring can work APPLICATIONCONTEXTCXT = new Classpa        Thxmlapplicationcontext ("Config/spring/beans.xml");  Productserviceproductservice = (productservice) cxt.getbean ("Productservicebean");        Take out an object producttypept = new ProductType ();        Pt.setname ("Cutter_point");        Pt.setnote ("very good");    Productservice.save (PT); } }


6. Summary

The above is the use of spring's dependency injection function to implement the corresponding function, we have this feature, after our STRUTS2 page controller action can be given to the spring hosting, so that in the Struts2 configuration file can implement dependency injection, And then the service layer is what many people call the DAO layer, called the Business layer bar, can be given to spring hosting, as long as we need to use spring's dependency injection function, as long as the corresponding place to add a note, such as

@Resource//Dependency Injection Sessionfactory

Sessionfactorysessionfactory;

This is a dependency injection on Sessionfactory, which is configured in spring, and then our service annotations

@Service//is equivalent to defining a bean in spring, which is the way of annotating <context:component-scanbase-package= "Com.cutter_point"/>

This is not configured, this is annotated, but has been given to spring hosting, so in the test class we can use directly, like this

Productservice Productservice = (productservice) cxt.getbean ("Productservicebean"); Take out an object

Because annotated spring will help us manage this class.


"Java EE Spring" 28, BA Sports Network-integrated HIBERNATE4+SPRING4 (3) Use annotations

Related Article

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.