Spring Data整合Mysql

附上示例程序的github地址:https://github.com/bjtudujunlin/SpringDataExample


1、 首先添加maven依赖

这里可以注意到,dependency标签里面没有添加版本信息,因为版本信息都在parent的pom文件里面进行了统一配置,解决不同jar包版本不兼容的问题。这里依赖了三个jar,spring-boot-starter-web是springboot提供的web支持的jar,内部封装了spring web开发需要的所有jar包。spring-boot-starter-data-jpa是springboot提供的jpa支持的jar包,mysql-connector-java是jdbc访问mysql的jar包。简单说下springboot,springboot解决了spring项目中存在的配置复杂的问题,比如spring web需要5、6个配置注解,springboot用1个注解就搞定了,很方便。

    <parent>

       <groupId>org.springframework.boot</groupId>

       <artifactId>spring-boot-starter-parent</artifactId>

       <version>1.4.2.RELEASE</version>

    </parent>

 

<dependencies>

       <dependency>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-starter-web</artifactId>

       </dependency>

       <dependency>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-starter-data-jpa</artifactId>

       </dependency>

       <dependency>

           <groupId>mysql</groupId>

           <artifactId>mysql-connector-java</artifactId>

       </dependency>

    </dependencies>

2、 配置数据源

在src/main/resources下面创建application.properties文件,内容如下,配置文件里面配置了datasource为mysql,jpa采用hibernate进行实现。

# DataSource settings: set here your own configurations for the database

# connection. In this example we have "netgloo_blog" as database name and

# "root" as username and password.

spring.datasource.url = jdbc:mysql://localhost:3306/test

spring.datasource.username = root

spring.datasource.password = 123456

 

# Keep the connection alive if idle for a long time (needed in production)

spring.datasource.testWhileIdle = true

spring.datasource.validationQuery = SELECT1

 

# Show or not log for each sql query

spring.jpa.show-sql = true

 

# Hibernate ddl auto (create, create-drop, update)

spring.jpa.hibernate.ddl-auto = update

 

# Naming strategy

spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

 

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is

# stripped before adding them to the entity manager)

 

# The SQL dialect makes Hibernate generate better SQL for the chosen database

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

3、 创建实体类

这里做了个简单例子,如下实体类Customer,用@Entity注解表明是一个实体类,默认对应了数据库表customer(这个表程序运行时会自动创建),Customer由三个属性,id是主键,自增长,firstName和lastName都是字符串。

package examples.mysql;

 

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

 

@Entity

public class Customer {

 

    @Id

    @GeneratedValue(strategy=GenerationType.AUTO)

    private Longid;

    private StringfirstName;

    private StringlastName;

 

    protected Customer() {}

 

    public Customer(StringfirstName, String lastName) {

        this.firstName =firstName;

        this.lastName =lastName;

    }

 

    @Override

    public String toString() {

        return String.format(

                "Customer[id=%d, firstName='%s', lastName='%s']",

                id, firstName, lastName);

    }

 

}

 

4、定义Repository接口

这里继承了CURDRepository,然后扩展了两个方法。

package examples.mysql;

 

import java.util.List;

 

import org.springframework.data.repository.CrudRepository;

 

public interface CustomerRepositoryextends CrudRepository<Customer, Long> {

   

    List<Customer> findByLastName(String lastName);

   

    List<Customer> findByFirstName(String firstName);  

}

5、运行程序

实体类和repository都有了,现在就剩把程序跑起来,定义Application类,内容如下。SpringBootApplication注解表明这是一个springboot的应用,EnableJpaRepositories添加了jpa支持,demo方法利用@bean注解同时返回了CommandLineRunner对象,表明这个方法会在springboot启动前加载运行,同时它的参数repository自动注入,springboot会在当前目录和子目录下搜索CustomerRepository类型的接口自动注入。

package examples.mysql;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.boot.CommandLineRunner;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.annotation.Bean;

import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

 

@SpringBootApplication

@EnableJpaRepositories

public class Application {

 

    private static final Logger log = LoggerFactory.getLogger(Application.class);

 

    public static void main(String[] args) {

       SpringApplication.run(Application.class);

    }

 

    /**

     * 返回CommandLineRunnerBean,在spring boot启动前加载并且执行

     *

     * @param repository

     * @return

     */

    @Bean

    public CommandLineRunner demo(CustomerRepositoryrepository) {

       return (args) -> {

           // save a couple of customers

           repository.save(new Customer("Jack","Bauer"));

           repository.save(new Customer("Chloe","O'Brian"));

           repository.save(new Customer("Kim","Bauer"));

           repository.save(new Customer("David","Palmer"));

           repository.save(new Customer("Michelle","Dessler"));

 

           // fetch all customers

           log.info("Customers found with findAll():");

           log.info("-------------------------------");

           for (Customercustomer : repository.findAll()) {

              log.info(customer.toString());

           }

           log.info("");

 

           // fetch an individual customer by ID

           Customer customer =repository.findOne(1L);

           log.info("Customer found with findOne(1L):");

           log.info("--------------------------------");

           log.info(customer.toString());

           log.info("");

 

           // fetch customers by last name

           log.info("Customer found with findByLastName('Bauer'):");

           log.info("--------------------------------------------");

           for (Customerbauer : repository.findByLastName("Bauer")) {

              log.info(bauer.toString());

           }

 

           // fetch customers by last name

           log.info("Customer found with findByFirstName('David'):");

           log.info("--------------------------------------------");

           for (Customerbauer : repository.findByFirstName("David")) {

              log.info(bauer.toString());

           }

           log.info("");

       };

    }

 

}

    在Application类中右键运行程序,就可以看见数据库中已经创建了表customer并且插入了几条数据了。

    几个类的布局如下:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值