使用 MySQL 的 Spring-boot 示例

我们将遵循 spring-boot 和 spring-data-jpa官方指南 。我们将使用 gradle 构建应用程序。

  1. 创建 gradle 构建文件

    build.gradle

    buildscript {
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.3.RELEASE")
        }
    }
    
    apply plugin: 'java'
    apply plugin: 'eclipse'
    apply plugin: 'idea'
    apply plugin: 'org.springframework.boot'
    
    jar {
        baseName = 'gs-accessing-data-jpa'
        version =  '0.1.0'
    }
    
    repositories {
        mavenCentral()
        maven { url "https://repository.jboss.org/nexus/content/repositories/releases" }
    }
    
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
    
    dependencies {
        compile("org.springframework.boot:spring-boot-starter-data-jpa")
        runtime('mysql:mysql-connector-java')
        testCompile("junit:junit")
    }
    
  2. 创建客户实体

    src / main / JAVA /你好/ Customer.java

    @Entity
    public class Customer {
    
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private Long id;
        private String firstName;
        private String lastName;
    
        protected Customer() {}
    
        public Customer(String firstName, 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);
        }
    }
    
  3. 创建存储库

    src / main / JAVA /你好/ CustomerRepository.java

    import java.util.List;
    import org.springframework.data.repository.CrudRepository;
    
    public interface CustomerRepository extends CrudRepository<Customer, Long> {
        List<Customer> findByLastName(String lastName);
    }
    
  4. 创建 application.properties 文件

    ################### DataSource Configuration ##########################
    jdbc.driverClassName=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/your_database_name
    jdbc.username=username
    jdbc.password=password
    
    init-db=false
    
    ################### Hibernate Configuration ##########################
    
    hibernate.dialect=org.hibernate.dialect.MySQLDialect
    hibernate.show_sql=true
    hibernate.hbm2ddl.auto=update
    
  5. 创建 PersistenceConfig.java 文件

在第 5 步中,我们将定义如何加载数据源以及我们的应用程序如何连接到 MySQL。上面的代码片段是我们连接 MySQL 所需的最低配置。这里我们提供两个 bean:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages="hello")
public class PersistenceConfig 
{
    @Autowired
    private Environment env;
 
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory()
    {
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
 
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(Boolean.TRUE);
        vendorAdapter.setShowSql(Boolean.TRUE);
 
        factory.setDataSource(dataSource());
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("hello");
 
        Properties jpaProperties = new Properties();
        jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
        factory.setJpaProperties(jpaProperties);
 
        factory.afterPropertiesSet();
        factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
        return factory;
    }
     
    @Bean
    public DataSource dataSource()
    {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.username"));
        dataSource.setPassword(env.getProperty("jdbc.password"));
        return dataSource;
    }
      
}
  • LocalContainerEntityManagerFactoryBean 这为我们提供了 EntityManagerFactory 配置的句柄,并允许我们进行自定义。它还允许我们在组件中注入 PersistenceContext,如下所示:
@PersistenceContext
private EntityManager em;
  • DataSource 这里我们返回 DriverManagerDataSource 的一个实例。它是标准 JDBC DataSource 接口的简单实现,通​​过 bean 属性配置普通的旧 JDBC 驱动程序,并为每个 getConnection 调用返回一个新的 Connection。请注意,我建议严格使用它进行测试,因为有更好的替代品,如 BasicDataSource 可用。请参阅此处了解更多详情
  1. 创建一个 Application 类

    src / main / JAVA /你好/ Application.java

     @SpringBootApplication
     public class Application {
    
         private static final Logger log = LoggerFactory.getLogger(Application.class);
    
         @Autowired
         private CustomerRepository repository;
    
         public static void main(String[] args) {
             SpringApplication.run(TestCoreApplication.class, args);
         }
    
         @Bean
         public CommandLineRunner demo() {
             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 (Customer customer : 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 (Customer bauer : repository.findByLastName("Bauer")) {
                     log.info(bauer.toString());
             }
             log.info("");
         };
     }
    

    }

  2. 运行应用程序

如果你使用的是像 STS 这样的 IDE ,只需右键单击你的项目 - >运行方式 - > Gradle(STS) 构建…在任务列表中,键入 bootRun 和 Run。

如果在命令行上使用 gradle ,则可以按如下方式运行应用程序:

./gradlew bootRun

你应该看到这样的东西:

== Customers found with findAll():
Customer[id=1, firstName='Jack', lastName='Bauer']
Customer[id=2, firstName='Chloe', lastName='O'Brian']
Customer[id=3, firstName='Kim', lastName='Bauer']
Customer[id=4, firstName='David', lastName='Palmer']
Customer[id=5, firstName='Michelle', lastName='Dessler']

== Customer found with findOne(1L):
Customer[id=1, firstName='Jack', lastName='Bauer']

== Customer found with findByLastName('Bauer'):
Customer[id=1, firstName='Jack', lastName='Bauer']
Customer[id=3, firstName='Kim', lastName='Bauer']