使用 MySQL 的 Spring-boot 示例
我們將遵循 spring-boot 和 spring-data-jpa 的官方指南 。我們將使用 gradle 構建應用程式。
-
建立 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") }
-
建立客戶實體
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); } }
-
建立儲存庫
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); }
-
建立 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
-
建立 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
可用。請參閱此處瞭解更多詳情
-
建立一個 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(""); }; }
}
-
執行應用程式
如果你使用的是像 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']