Spring Boot Learning Note-0 XML configuration JPA

Source: Internet
Author: User
Tags sort

Today we have configured the JPA 0 XML configuration for Springboot, which is finally configured and shared as a learning configuration for springboot and JPA, most of which are XML-based configurations.

JPA configuration Reference Web, mainly XML configuration

Relax and enjoy the fun of springdata

Springboot's Learning Reference

Spring Boot Learning notes-developing the first application

Spring Boot Learning notes-custom configuration

Application.yml

DB:
  driver:com.mysql.jdbc.Driver
  url:jdbc:mysql://127.0.0.1:3306/springbootdb
  username:root
  Password: password
hibernate:
  show_sql:true
  format_sql:true
  ejb.naming_strategy: Org.hibernate.cfg.ImprovedNamingStrategy
  Dialect:org.hibernate.dialect.MySQL5InnoDBDialect
  Hbm2ddl.auto:update
PACKAGES.TO.SCAN:COM.GWC

The JPA configuration consists of the following three local configuration data sources DataSource configuration Entitymanagerfactory transaction Manager configuration

The configuration is as follows (the key location already has comments)

Package com.gwc.config;
Import Com.alibaba.druid.pool.DruidDataSource;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
Import Org.springframework.context.annotation.PropertySource;
Import org.springframework.core.env.Environment;
Import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
Import Org.springframework.orm.hibernate5.HibernateExceptionTranslator;
Import Org.springframework.orm.jpa.JpaTransactionManager;
Import Org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
Import Org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
Import Org.springframework.transaction.PlatformTransactionManager;

Import org.springframework.transaction.annotation.EnableTransactionManagement;
Import Javax.sql.DataSource;

Import java.util.Properties;
 /** * JPA configuration classes, including data sources, transaction management, etc. * Created by Gwcheng on 2017/4/21. *//indicates that the class uses spring basedJava configuration @Configuration//Read config file, read @PropertySource via Environment ("CLASSPATH:APPLICATION.YML")//scan the package of The annotated configuration class for Spring Data repositories @EnableJpaRepositories (basepackages = "Com.gwc.dao")//Ena Bles Spring ' s annotation-driven Transaction management @EnableTransactionManagement public class Jpaconfig {@Autowir

    Ed private Environment env; /** * 1. Configure Data Source * * @return DataSource */@Bean public DataSource DataSource () {Druidda
        Tasource Source = new Druiddatasource ();
        Source.setdriverclassname (Env.getrequiredproperty ("Db.driver"));
        Source.seturl (Env.getrequiredproperty ("Db.url"));
        Source.setusername (Env.getrequiredproperty ("Db.username"));
        Source.setpassword (Env.getrequiredproperty ("Db.password"));
    return source; }/** * 2. Configure Entitymanagerfactory * * @return */@Bean public Localcontainerentitymanagerf Actorybean EntitymanagErfactory () {Localcontainerentitymanagerfactorybean factory = new Localcontainerentitymanagerfactorybean ();
        Configure Data source Factory.setdatasource (DataSource ());
        Vendoradapter Factory.setjpavendoradapter (New Hibernatejpavendoradapter ());
        Entity Packet Scan Path Factory.setpackagestoscan (Env.getrequiredproperty ("Packages.to.scan"));
        JPA attribute Factory.setjpaproperties (Hibernateproperties ());
        Factory.afterpropertiesset ();
    return factory; }/** * 3. Transaction Manager Configuration * * @return * * @Bean public Platformtransactionmanager Transactionmana
        Ger () {Jpatransactionmanager manager = new Jpatransactionmanager ();
        Manager.setentitymanagerfactory (Entitymanagerfactory (). GetObject ());
    Return manager; }/** * Convert hibernateexceptions to Dataaccessexceptions */@Bean public hibernateexceptiontranslator hi Bernateexceptiontranslator () {return new HibernAteexceptiontranslator (); }/** * Hibernate configuration * @return */private Properties hibernateproperties () {Properties Pro
        perties = new Properties ();
        Displays the SQL statement properties.put ("Hibernate.show_sql", Env.getrequiredproperty ("Hibernate.show_sql"));
        Format SQL statement properties.put ("Hibernate.format_sql", Env.getrequiredproperty ("Hibernate.format_sql"));
        Dialect properties.put ("Hibernate.dialect", Env.getrequiredproperty ("Hibernate.dialect"));
        Automatic generation of Table Properties.put ("Hibernate.hbm2ddl.auto", Env.getrequiredproperty ("Hibernate.hbm2ddl.auto")); Name Strategy Properties.put ("Hibernate.ejb.naming_strategy", Env.getrequiredproperty ("Hibernate.ejb.naming_strategy"))
        ;
    return properties;
 }

}

Develop your own DAO inheritance Jparepository

Package Com.gwc.dao;

Import Com.gwc.entity.SysMenu;
Import org.springframework.data.jpa.repository.JpaRepository;

/**
 * Created by Gwcheng on 2017/4/21.
 */Public
Interface Sysmenurepository extends jparepository<sysmenu,long> {

}

Sysmenu is the System menu class

Package com.gwc.entity;

Import Com.gwc.enums.MenuType;

Import javax.persistence.*;
Import java.util.Date;

/**
 * System Menu
 * Created by Gwcheng on 2017/4/21.
 *
/@Entity public
class Sysmenu {
    @Id
    @GeneratedValue (strategy = generationtype.auto)/
    * PRIMARY KEY */
    private Long ID;
    /* Name
     *
    /@Column (length =)
    private String name;
    /*
    Parent ID
     */
    private Long parentid;
    /* Order
     *
    /@Column (name = "Orders")
    private Integer order;
    /*
    type, module (modules), page (page)/
    @Column (length = 6)
    private String type;
    /* Link (type is page with URL)
     *
    /@Column (length = +)
    private String URL;
    /* icon (type is icon for module)
     *
    /@Column (length = +)
    private String icon;
    /*
    Create Time
     */
    private Date createtime;
    /*
    Modify Time
     */
    private Date updatetime;

   // ... Omit Getter Setter method and tostring method 
}

Test cases are as follows

Package COM.GWC;
Import com.gwc.config.MainApplication;
Import Com.gwc.dao.SysMenuRepository;
Import Com.gwc.entity.SysMenu;
Import Com.gwc.enums.MenuType;
Import Org.junit.Test;
Import Org.junit.runner.RunWith;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.boot.test.context.SpringBootTest;
Import Org.springframework.data.domain.Page;
Import Org.springframework.data.domain.PageRequest;
Import org.springframework.data.domain.Pageable;
Import Org.springframework.data.domain.Sort;

Import Org.springframework.test.context.junit4.SpringRunner;
Import Java.util.Date;

Import java.util.List; @RunWith (Springrunner.class) @SpringBootTest (classes = mainapplication.class) public class Sysmenurepositorytests {@

    Autowired sysmenurepository sysmenurepository;
        @Test public void Testpageandsort () {Sort.order order = new Sort.order (Sort.Direction.DESC, "order");
        Sort sort = new sort (order); pageable pageable = new PAgerequest (0,2,sort);
        page<sysmenu> page = Sysmenurepository.findall (pageable);
        For (Sysmenu sysMenu:page.getContent ()) {System.out.println (sysmenu);
        }} @Test public void Testsort () {Sort sort = new sort (Sort.Direction.DESC, "order");
        list<sysmenu> sysmenulist = sysmenurepository.findall (sort);
        for (Sysmenu sysmenu:sysmenulist) {System.out.println ("sort field:" +sysmenu.getorder ());
        }} @Test public void Testsave () {Sysmenu sysmenu = new Sysmenu ();

    Sysmenurepository.save (Sysmenu);
        } @Test public void Testfindall () {list<sysmenu> sysmenulist = Sysmenurepository.findall ();
        for (Sysmenu sysmenu:sysmenulist) {System.out.println (sysmenu);

    }} @Test public void Testdelete () {sysmenurepository.delete (1L); } @Test public void Testfindone () {Sysmenu Sysmenu = SysmenurepositOry.findone (1L);
    System.out.println (Sysmenu);
 }


}
Reference Documents

Spring Boot Learning notes-custom configuration
Spring Boot Learning notes-developing the first application
Relax and enjoy the fun of springdata

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.