Spring boot integrates spring data JPA

Source: Internet
Author: User
Tags table name

The structure of this article:
-What is Springdata JPA
-Springboot Integrated Spring data JPA

The core interface of Spring Data repository is repository (it seems to be nothing to be surprised). This interface requires the domain class with the ID type of the domain class as the parameter. This interface is primarily for you to know the type of interface that inherits this class. Crudrepository provides some common crud methods for managed entity classes.

2. Springboot Integrated Spring data JPA

By default you have already built the spring boot project, for the new Spring boot project, please refer to:
Springboot Demo
Springboot Integration MyBatis 2.1. First import the jar package

Springboot integrates spring data JPA to first import the dependent jar packages. The following dependencies are added in the Pom.xml file:

    <!--SPRING-DATA-JPA--<dependency> <groupid>org.springframework.data</grou pid> <artifactId>spring-data-jpa</artifactId> </dependency> <dependenc Y> <groupId>org.hibernate</groupId> <artifactid>hibernate-entitymanager</a rtifactid> </dependency> <dependency> <groupid>org.aspectj</groupid&gt
            ; <artifactId>aspectjweaver</artifactId> </dependency> <!--data source Spring data JPA requires To connect pools with C3P0-<dependency> <groupId>com.mchange</groupId> &LT;ARTIFAC
                Tid>c3p0</artifactid> <version>0.9.5.2</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifa Ctid>commons-logging</artifactid> </exclusion> </exclusions> </dependenc
 Y>
2.2 Configuring DataSource

Create a new Dbconfig.java file configuration data source.

Package com.example.config;

Import java.beans.PropertyVetoException;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;

Import org.springframework.core.env.Environment;

Import Com.mchange.v2.c3p0.ComboPooledDataSource;

    @Configuration public class Dbconfig {@Autowired private environment env; @Bean (name= "DataSource") public Combopooleddatasource DataSource () throws Propertyvetoexception {Combopooledd
        Atasource DataSource = new Combopooleddatasource ();
        Datasource.setdriverclass (Env.getproperty ("Ms.db.driverClassName"));
        Datasource.setjdbcurl (Env.getproperty ("Ms.db.url"));
        Datasource.setuser (Env.getproperty ("Ms.db.username"));
        Datasource.setpassword (Env.getproperty ("Ms.db.password"));
        Datasource.setmaxpoolsize (20);
        Datasource.setminpoolsize (5);
  Datasource.setinitialpoolsize (10);      Datasource.setmaxidletime (300);
        Datasource.setacquireincrement (5);

        Datasource.setidleconnectiontestperiod (60);
    return dataSource;
 }

}
2.3. Add Database connection Information

Add the database connection information in the configuration file application.properties as follows:

Ms.db.driverclassname=com.mysql.jdbc.driver
ms.db.url=jdbc:mysql://localhost:3306/msm?prepstmtcachesize= 517&cacheprepstmts=true&autoreconnect=true&characterencoding=utf-8&allowmultiqueries=true
Ms.db.username=root
ms.db.password=admin
ms.db.maxactive=500
2.4 Configuring Jpaconfig

The contents of the new Jpaconfig.java file are as follows:

Package com.example.config;
Import Java.util.HashMap;

Import Java.util.Map;
Import Javax.persistence.EntityManagerFactory;

Import Javax.sql.DataSource;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
Import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
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; @Configuration//Here is the package name where your DAO file is located @EnableJpaRepositories ("Com.example.*.dao") @EnableTransactionManagement public

    Class Jpaconfig {@Autowired private DataSource DataSource; @Bean Public Entitymanagerfactory EntitymanagerfactorY () {hibernatejpavendoradapter vendoradapter = new Hibernatejpavendoradapter ();
        Localcontainerentitymanagerfactorybean factory = new Localcontainerentitymanagerfactorybean ();
        Factory.setjpavendoradapter (Vendoradapter);
        Here Com.example.*.model is the package name Factory.setpackagestoscan ("Com.example.*.model") where your Java bean resides;

        Factory.setdatasource (DataSource);
        map<string, object> jpaproperties = new hashmap<string, object> ();
        Jpaproperties.put ("Hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");

        Jpaproperties.put ("Hibernate.jdbc.batch_size", 50);
        Factory.setjpapropertymap (jpaproperties);
        Factory.afterpropertiesset ();
    return Factory.getobject (); } @Bean Public Platformtransactionmanager TransactionManager () {Jpatransactionmanager Txmanager = new J
        Patransactionmanager ();
        Txmanager.setentitymanagerfactory (Entitymanagerfactory ()); Return Txmanager;
 }
}
2.5 Create a new entity class for the corresponding database table. (i.e. Java bean)
Note the use of the
label @Entity @Table (name = "Sec_user")
, @Entity indicates that this is an entity class, @Table (name = "Sec_user") sec_user is the corresponding table name in the database

@Id
@GeneratedValue corresponding Id 
@Column (name = "name") corresponds to the column name of the column in the database, that is, the property name
Package Com.example.base.model;

Import Java.util.Date;
Import Javax.persistence.Column;
Import javax.persistence.Entity;
Import Javax.persistence.GeneratedValue;
Import Javax.persistence.Id;

Import javax.persistence.Table;

Import Com.fasterxml.jackson.annotation.JsonIgnore;
    @Entity @Table (name = "Sec_user") public class User {@Id @GeneratedValue private Integer Id;
    @Column (name = "name") private String name;
    @Column (name = "password") private String password;
    @Column (name = "username") private String username;
    @Column (name = "division_id") private Integer Divisionid;
    @Column (name = "email") Private String email;
    @Column (name = "gender") private String gender;
    @Column (name = "Mobilephone") private String mobilephone;
    @Column (name = "Telephone") private String telephone;
    @Column (name = "User_type") private Integer usertype;
    @Column (name = "create_by") private String CreateBy; @Column (name = "Create_time") private Date createtime;
    @Column (name = "update_by") private String Updateby;
    @Column (name = "Update_time") private Date updatetime;
    @Column (name = "Disabled") private Integer disabled;
    @Column (name = "Theme") private String theme;

    @Column (name = "Is_ldap") private Integer Isldap;
    Public String GetName () {return name;
    } public void SetName (String name) {this.name = name;
    } @JsonIgnore Public String GetPassword () {return password;
    } public void SetPassword (String password) {this.password = password;
    } public String GetUserName () {return username;
    } public void Setusername (String username) {this.username = username;
    } public Integer Getdivisionid () {return divisionid;
    } public void Setdivisionid (Integer divisionid) {This.divisionid = Divisionid;
  } public String Getemail () {      return email;
    } public void Setemail (String email) {this.email = email;
    } public String Getgender () {return gender;
    } public void Setgender (String gender) {This.gender = gender;
    } public String Getmobilephone () {return mobilephone;
    } public void Setmobilephone (String mobilephone) {this.mobilephone = Mobilephone;
    } public String Gettelephone () {return telephone;
    } public void Settelephone (String telephone) {this.telephone = telephone;
    } public Integer Getusertype () {return usertype;
    } public void Setusertype (Integer usertype) {this.usertype = usertype;
    } public String Getcreateby () {return createby;
    } public void Setcreateby (String createby) {this.createby = CreateBy;
    Public Date Getcreatetime () {return createtime; } public void Setcreatetime (Date createtime) {this.createtime = Createtime;
    } public String Getupdateby () {return updateby;
    } public void Setupdateby (String updateby) {this.updateby = Updateby;
    Public Date Getupdatetime () {return updatetime;
    } public void Setupdatetime (Date updatetime) {this.updatetime = UpdateTime;
    } public Integer getdisabled () {return disabled;
    } public void setdisabled (Integer disabled) {this.disabled = disabled;
    } public String Gettheme () {return theme;
    } public void SetTheme (String theme) {this.theme = theme;
    } public Integer Getisldap () {return isldap;
    } public void Setisldap (Integer isldap) {this.isldap = Isldap;
    } public Integer GetId () {return id;
    } public void SetId (Integer id) {this.id = ID; }
}
2.5 Writing the DAO layer of Spring data JPA (play OH)

First, let's look at the naming conventions of spring data JPA before we start writing a simple test example.


Example:
New Userjpadao class inherits Jparepository

package Com.example.base.dao;
Import Org.springframework.data.jpa.repository.JpaRepository;
Import Org.springframework.data.jpa.repository.Query;

Import Org.springframework.data.repository.query.Param;

Import Com.example.base.model.User;
 /** * the Interface Userjpadao.
     * @author Abel */public interface Userjpadao extends Jparepository<user, long> {/** * Find by name.

    * * @param name The name * @return the user */user findbyname (String name);
     /** * Find by name and user name. * If the parameter name consists of more than one letter, capitalize the first letter. Do not use hump naming, JPA does not recognize hump * @param name The name * @param age of the age * @return the user */user Findbyname

    Andusername (String name, Integer age);
     /** * Find user. * User is @entity name * @param name the name * @return the user */@Query ("from User U where U.name=:name"
) User Finduser (@Param ("name") String name); }
The 2.6 service layer is written (this step is no different from spring MVC.) )

The service code is as follows. (Here I just wrote a method of DAO)

Package com.example.base.service;
Import Com.example.base.model.User;

/**
 * The Interface userservice.
 */Public
interface UserService {

    /**
     * Gets the user by name.
     *
     * @param username The user name
     * @return the user by name
     *
    /Public user getuserbyname (String Userna me);
}

The implementation is as follows:

Package Com.example.base.service.Impl;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Service;
Import Com.example.base.dao.UserJpaDao;
Import Com.example.base.model.User;
Import Com.example.base.service.UserService;
/**
 * 
 * @ClassName userserviceimpl
 * @author Abel
 * @date November 10, 2016
* * @Service public class Userserviceimpl implements UserService {

    @Autowired
    private Userjpadao Userjpadao;

    /**
     * 
     * @param UserName
     * @return * * *
    @Override public
    User Getuserbyname (String username) {
        return userjpadao.findbyname (username);
    }
}
2.7 Controller Writing
Package Com.example.base.controller;

Import Javax.servlet.http.HttpServletRequest;
Import Java.util

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.