Java for Web Learning Notes (102): Using JPA (2) Transaction (__java) in the spring framework

Source: Internet
Author: User
configuration of the context

/* "3" SET Transaction Management * 3.1 "allows the @transactional tag to be valid * makes @transactional effective and can be dynamically intercepted by means of a method identified in the Bean, which is Advice by the spring framework. Similar to @enableasync, you need to set up @enabletransactionmanagement. But note: For method enhancements, we should use the same approach, and if configured differently, spring will choose one of them, causing uncertainty. Therefore, @EnableAsync and @enabletransactionmanagement are required to use the same advicemode (PROXY or ASPECTJ) and the same proxytargetclass values,
 Simply can be set separately as proxy and flase. *➤advicemode.proxy represents a method that is wrap by a class that passes a proxy. Dynamic Proxy (Proxytargetclass = False) encapsulates the method only when the identity method is invoked, and cglib (Proxytargetclass = True) override all methods.
 That is, the method is also enhanced when calling the Unlabeled method (the sense should be that the instance is being created, and therefore Cglib cannot use final Class).
 * 1, usually recommended Proxytargetclass = False, which means that this method must be in the interface, and the method call in this class tag is invalid, must be called outside to be valid.
 * 2, if we want to use in a non-interface other public method, we need to use Cglib Proxy, that is, Proxytargetclass = True,cglib Proxy is the disadvantage of the constructor is called two times. *➤ADVICEMODE.ASPECTJ is load-time weaving enabled, that is, when load, modify the compiled bytecode, add related methods to add, can be used for final classes and methods, can be used in class method calls, It can even be used for non-spring beans (for traditional code modifications). With ASPECTJ, you also need to add * @EnableLoadTimeWeaving (aspectjweaving=enableloadtimeweaving.aspectjweaving.enabled) * and add in pom.xml: * <dependency> * <groupId>org.springframework</groupId> * <artifactId>spring-aspects</artifactId> * <version>4.0.2.RELEASE</version> * <scope>runtime</scope> * </dependency> * When multiple When a proxy exists, we also need to consider the order of the proxy. If transaction proxy could not actually execute asynchronously before the asynchronous proxy, we set the appropriate order.
It is clear that asynchronous execution should be more preferred, otherwise the method labeled @async is invoked within @transactional, and asynchrony will not take effect. * */@Configuration @EnableScheduling @EnableAsync (mode = Advicemode.proxy, Proxytargetclass = false, order = Ordered.high est_precedence) @EnableTransactionManagement (mode = Advicemode.proxy, Proxytargetclass = false, order = Ordered.lowest_ Precedence) @ComponentScan (basepackages = "Cn.wei.flowingflying.chapter21.site", excludefilters = @Componen Tscan.filter ({controller.class, controlleradvice.class})) public class Rootcontextconfiguration implements
    Asyncconfigurer, schedulingconfigurer{private static final Logger log = Logmanager.getlogger (); private static final Logger Schedulinglogger= Logmanager.getlogger (Log.getname () + ". [

   Scheduling] ");
    /* "1" set DataSource.
    * Mode One: If we simply use a JDBC connection, this approach is only used in temporary projects, may be test code, or may be the prototype code * @Bean * Public DataSource Springjpadatasource () {
    * Drivermanagerdatasource DataSource = new Drivermanagerdatasource ();
    * Datasource.seturl ("JDBC:MYSQL://LOCALHOST/SPRINGJPA");
    * Datasource.setusername ("Tomcatuser");
    * Datasource.setpassword ("password1234");
    * Return dataSource; *  * mode Two: Use the connection address pool provided by C3P0. We need to add * <dependency> * <groupId>mysql</groupId> * <artifactid>mysq in Pom.xml l-connector-java</artifactid> * <version>5.1.44</version> * </dependency> * <d
    ependency> * <groupId>com.mchange</groupId> * <artifactId>c3p0</artifactId> * <version>0.9.5.2</version> * </dependency> * Since we do not use Tomcat's connection pool, we need to be careful when the war is uninstalledShut down.
    * The code that is closed can see http://blog.csdn.net/flowingflying/article/details/51932956. * @Bean * Public DataSource Springjpadatasource () throws propertyvetoexception {* Combopooleddatasource data
    Source = new Combopooleddatasource ();
    * Datasource.setdriverclass ("Com.mysql.jdbc.Driver"); * Datasource.setjdbcurl ("jdbc:mysql://localhost/springjpa?usessl=true&useunicode=true&characterencoding
    =utf-8&autoreconnect=true ");
    * Datasource.setuser ("Tomcatuser");		
    * Datasource.setpassword ("password1234");
    * Datasource.setminpoolsize (2);
    * Datasource.setacquireincrement (1);
    * Datasource.setmaxpoolsize (20);		
    * Datasource.setmaxidletime (2);
    * Datasource.setinitialpoolsize (2);
    * DATASOURCE.SETIDLECONNECTIONTESTPERIOD (300);
    * Return dataSource;
    * In addition to C3P0, we can also use the Apache Commons dbcp,apache commonspool to cascade the DataSource of the pooled connection. *  * mode three: the way before the tomcat context configuration.
    That's the way the examples are given.
  */  @Bean public DataSource Springjpadatasource () {jndidatasourcelookup lookup = new Jndidatasourcelookup ();
    Return Lookup.getdatasource ("Jdbc/learntest"); }/* "2" creates persistence unit. In spring, We need a bean to implement Org.springframework.orm.jpa.AbstractEntityManagerFactoryBean, which will create Sharedentitymanagerbean to provide a line for our repository Cheng Ann
    The whole business. * Mode one: Through the Localentitymanagerfactorybean implementation, using the/meta-inf/persistence.xml configuration file, set the persistence unit name to the * @Bean * pub Lic Localentitymanagerfactorybean Entitymanagerfactorybean () {* Localentitymanagerfactorybean factory = new LocalE
    Ntitymanagerfactorybean ();
    * Factory.setpersistenceunitname ("SPRINGJPA");
    * Factory.setjpavendoradapter (new Hibernatejpavendoradapter ());
    * Factory.setdatasource (This.springjpadatasource ());
    * Return factory; *  * mode two: Localcontainerentitymanagerfactorybean implementation, to specify the XML configuration file * @Bean * public Localcontainerentitymana Gerfactorybean Entitymanagerfactorybean (){* Localcontainerentitymanagerfactorybean factory = new Localcontainerentitymanagerfactorybean ();
    * Factory.setpersistencexmllocation ("Classpath:com/wrox/config/persistence.xml");
    * Factory.setpersistenceunitname ("SPRINGJPA");
    * Factory.setjpavendoradapter (new Hibernatejpavendoradapter ());
    * Factory.setdatasource (This.springjpadatasource ());
    * Return factory;
    *  * mode three: Through the Localcontainerentitymanagerfactorybean implementation, configuration in the code, does not apply to the XML configuration file. * That is, the code given by the small example. In the previous study, we through Persistence.xml to set up, can be compared, the actual is the same. * * @Bean public Localcontainerentitymanagerfactorybean Entitymanagerfactorybean () {//2.1) creates a map to store JPA Pro
        Perties configuration map<string, object> properties = new hashtable<> ();
        Properties.put ("Javax.persistence.schema-generation.database.action", "none"); 2.2 Create hibernate adapter as factory adaptor, providing a lot of information//➤ equivalent Persistence.xml <provider>org.hibernate.jpa.hi BernatepersistenceProvider</provider>//➤ tells Sharedentitymanagerbean the entitymanagerfactory of the proxy it needs (extended to be Hibernateentitymanager
        Factory) and Entitymanager (extended to Hibernateentitymanager).
        ➤ told spring to translate hibernate related ORM exceptions for DataAccessException. ➤ can be configured correctly for hibernate is the database language. The traditional dialect is MySQL 4.x, in order to avoid the ambiguity on the version, it is best to explicitly set//-MySQL 4.x Generic:org.hibernate.dialect.MySQLDialect (default for MySQL Selection)//-MySQL 4.x MyISAM Engine:org.hibernate.dialect.MySQLMyISAMDialect//-MySQL 4.x InnoDB E Ngine:org.hibernate.dialect.MySQLInnoDBDialect//-MySQL 5.x+ Generic + MyISAM:org.hibernate.dialect.MySQL5 Dialect//-MySQL 5.x+ InnoDB Engine:org.hibernate.dialect.MySQL5InnoDBDialect Hibernatejpavendorada
        Pter adapter = new Hibernatejpavendoradapter ();

        Adapter.setdatabaseplatform ("Org.hibernate.dialect.MySQL5InnoDBDialect");
  Localcontainerentitymanagerfactorybean factory = new Localcontainerentitymanagerfactorybean ();      Factory.setjpavendoradapter (adapter); 2.3 Set DataSource, which is equivalent to <non-jta-data-source> and Transaction-type in the XML configuration as resource_local.
        If Setjtadatasource () is used, the equivalent of <jta-data-source> and Transaction-type is JTA, which is typically used for multiple data sources.
        Factory.setdatasource (This.springjpadatasource ()); 2.4) Set the scan path.
        Equivalent to <exclude-unlisted-classes>true</exclude-unlisted-classes&gt, and list entity class in <class>
        Factory.setpackagestoscan ("cn.wei.flowingflying.chapter21.site.entity");
        Factory.setsharedcachemode (sharedcachemode.enable_selective);
        Factory.setvalidationmode (Validationmode.none);
        Factory.setjpapropertymap (properties);
    return factory; /** 3.2 "Set Platformtransactionmanager Bean * When we use @enabletransactionmanagement, we must set Platformtransactionmanager bea N.
    For JPA, using Jpatransactionmanager, you need to associate entitymanagerfactory in the constructor. * This example gives the code for a single Platformtransactionmanager bean. If multiple platformtransactionmanager beans exist, Jpatransactionmanager is the default transaction manager, the following is the example * public someservice{* @Transactional the public void Actionone ();//using the default TransactionManager *
    @Transactional ("Jpatransactionmanager") public void Actiontwo ();
    * @Transactional ("Datasourcetransactionmanager") public void Actionthree (); * The other platformtransactionmanager are set as follows: * 1, set up other Platformtransactionmanager examples: * @Bean * Public platfor Mtransactionmanager Datasourcetransactionmanager () {* Return to new Datasourcetransactionmanager (This.springJpaDataSo Urce ());
    For simple data source operations. *} * 2, set default values. For the jta@transactional tag, spring uses the default Platformtransactionmanager, which is returned by Transactionmanagementconfigurer if multiple transaction managers Transactionmanagementconfigurer is called Txmanager, if we use XML as a configuration (you can search on the web), it is more clear. If we use the @transactional tag for spring, you can specify which platformtransactionmanager to use in the tag, and if not, use the default, That is, transaction management returns a Bean (the first) to implement Platformtransactionmanager named Txmanager. But if you're storing multiple platformtransactionmanagers, it's best to specify which is the default, which is the Transactionmanagementconfigurer interface in springAnnotationdriventransactionmanager () is returned, so you need to inherit transactionmanagementconfigurer, that is, * public class Rootcontextconfiguration implements Asyncconfigurer, Schedulingconfigurer, transactionmanagementconfigurer{* @Ove Rride * Public Platformtransactionmanager Annotationdriventransactionmanager () {* Return This.datasou
    Rcetransactionmanager (); * There is a problem with this: you cannot return This.jpatransactionmanager () here. Factory.setdatasource (This.springjpadatasource ()) in Entitymanagerfactorybean () The Annotationdriventransactionmanager () method is invoked, and if the Annotationdriventransactionmanager () method calls Jpatransactionmanager (),
    Then Jpatransactionmanager () will call Entitymanagerfactorybean, this is a loop, it will be an error. * If there is only one data source, as shown in this example, we do not need to do this, but if there are multiple data sources, we need to consider. * * @Bean public Platformtransactionmanager Jpatransactionmanager () {Return to New Jpatransactionmanager (this.
    Entitymanagerfactorybean (). GetObject ()); }
    .....	
}

RELATED links: My professional Java for WEB applications related articles

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.