spring boot 整合spring data jpa

來源:互聯網
上載者:User

本文結構:
- 什麼是springdata jpa
- springboot 整合spring data jpa

Spring Data Repository的核心介面是Repository(好像也沒什麼好驚訝的)。這個介面需要領域類(Domain Class)跟領域類的ID類型作為參數。這個介面主要是讓你能知道繼承這個類的介面的類型。CrudRepository 供了對被管理的實體類的一些常用CRUD方法。

2. springboot 整合spring data jpa

預設你已經構建好了spring boot 項目,關於spring boot項目的建立,請參考:
springboot Demo
springboot 整合mybatis 2.1. 首先匯入jar 包

springboot 整合spring data jpa 首先要匯入依賴的jar包。pom.xml 檔案中新增如下依賴:

    <!-- spring-data-jpa -->        <dependency>            <groupId>org.springframework.data</groupId>            <artifactId>spring-data-jpa</artifactId>        </dependency>        <dependency>            <groupId>org.hibernate</groupId>            <artifactId>hibernate-entitymanager</artifactId>        </dependency>        <dependency>            <groupId>org.aspectj</groupId>            <artifactId>aspectjweaver</artifactId>        </dependency>    <!--data source  spring data jpa 需要用c3p0 串連池-->        <dependency>            <groupId>com.mchange</groupId>            <artifactId>c3p0</artifactId>            <version>0.9.5.2</version>            <exclusions>                <exclusion>                    <groupId>commons-logging</groupId>                    <artifactId>commons-logging</artifactId>                </exclusion>            </exclusions>        </dependency>
2.2 配置datasource

建立DBConfig.java 檔案 配置資料來源。

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;@Configurationpublic class DBConfig {    @Autowired    private Environment env;    @Bean(name="dataSource")    public ComboPooledDataSource dataSource() throws PropertyVetoException {        ComboPooledDataSource 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. 添加資料庫連接資訊

在設定檔application.properties中添加資料庫連接資訊如下:

ms.db.driverClassName=com.mysql.jdbc.Driverms.db.url=jdbc:mysql://localhost:3306/msm?prepStmtCacheSize=517&cachePrepStmts=true&autoReconnect=true&characterEncoding=utf-8&allowMultiQueries=truems.db.username=rootms.db.password=adminms.db.maxActive=500
2.4 配置JpaConfig

建立JpaConfig.java 檔案內容如下:

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//此處是你dao檔案所在的包名@EnableJpaRepositories("com.example.*.dao")@EnableTransactionManagementpublic class JpaConfig {    @Autowired    private DataSource dataSource;    @Bean    public EntityManagerFactory entityManagerFactory() {        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();        factory.setJpaVendorAdapter(vendorAdapter);        //此處com.example.*.model是你的java bean所在的包名        factory.setPackagesToScan("com.example.*.model");        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 JpaTransactionManager();        txManager.setEntityManagerFactory(entityManagerFactory());        return txManager;    }}
2.5 建立對應資料庫表的實體類。(也就是java bean )
注意 @Entity@Table(name = "sec_user")標籤的使用,@Entity表示這個是一個實體類,@Table(name = "sec_user") 中sec_user 是資料庫中對應的表名@Id@GeneratedValue 對應ID @Column(name = "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 編寫spring data jpa 的dao層(重頭戲哦)

首先我們先瞭解一下 spring data jpa 的命名規範,然後再開始編寫一個簡單的測試例子。


例子:
建立UserJpaDao類繼承 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.     * 如果參數名為多個字母組成,請首字母大寫。勿使用駝峰命名,jpa不識別駝峰     * @param name the name     * @param age the age     * @return the user     */    User findByNameAndUsername(String name, Integer age);    /**     * Find user.     * User為@Entity 的名字     * @param name the name     * @return the user     */    @Query("from User u where u.name=:name")    User findUser(@Param("name") String name);}
2.6 service 層的編寫(這一步和Spring mvc 已經沒有什麼差別的了。)

service 代碼如下。(此處我就僅僅寫了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 username);}

實現如下:

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 2016年11月10日 */@Servicepublic class UserServiceImpl implements UserService {    @Autowired    private UserJpaDao userJpaDao;    /**     *      * @param UserName     * @return     */    @Override    public User getUserByName(String username) {        return userJpaDao.findByName(username);    }}
2.7 controller 編寫
package com.example.base.controller;import javax.servlet.http.HttpServletRequest;import java.util

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.