上一篇我们已经成功搭建了一个SpringBoot的工程,在这个基础上实现一个通信录功能的CURD的Demo程序,本篇讲述如何构建后端部分。
由于重点是演示SpringBoot,我们就简化这个通信录,在Mysql中新建一个Person表,包含Id,Name和Phone三个字段,初始化SQL语句如下:
CREATE TABLE `Person` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(11) DEFAULT NULL,
`phone` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
为了在SpringBoot中连接Mysql数据库,首先在pom文件中增加如下三个依赖:
<dependency>
<groupId>org.springframework.datagroupId>
<artifactId>spring-data-jpaartifactId>
dependency>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-entitymanagerartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
增加后进行Maven Update Project后在Maven Dependency中就可以看到新增的依赖包。
新建一个package,名字为jpa,用来放数据库相关的处理的类,新建一个类DataSourceConfig.java,代码如下:
package com.springBoot.curdDemo.jpa;
import java.util.Properties;
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.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://***.***.***.***:3306/curdDemo?useUnicode=true&characterEncoding=UTF-8");// 填入你的mysql的访问url
dataSource.setUsername("***");// mysql用户名
dataSource.setPassword("***");// mysql访问密码
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(dataSource);
entityManagerFactory.setPackagesToScan("com.springBoot.curdDemo.jpa.entity");// mapping类的存放路径
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
entityManagerFactory.setJpaVendorAdapter(vendorAdapter);
Properties additionalProperties = new Properties();
additionalProperties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
additionalProperties.put("hibernate.show_sql", "false");
additionalProperties.put("hibernate.hbm2ddl.auto", "none");
entityManagerFactory.setJpaProperties(additionalProperties);
return entityManagerFactory;
}
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
entityManagerFactory.getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
@Autowired
private DataSource dataSource;
@Autowired
private LocalContainerEntityManagerFactoryBean entityManagerFactory;
}
这个类用于配置和MySql的连接以及Hibernate的属性,Spring 3以后的中心思想就是”约定大于配置”,这里配置了DataSource, LocalContainerEntityManagerFactoryBean, JpaTransactionManager等Bean在Spring的上下文中,由于我们只配置了这些数据库相关的Bean,Spring会自动使用这些Bean作为JPA的底层配置。
我们配置了mapping类的存放路径为com.springBoot.curdDemo.jpa.entity,那么下一步就新建这个package,然后建立一个类来mapping数据库中的Person表。该类代码如下:
package com.springBoot.curdDemo.jpa.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "Person")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "phone")
private String phone;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
数据库部分最后构建一个Respository接口,代码如下:
package com.springBoot.curdDemo.jpa;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.springBoot.curdDemo.jpa.entity.Person;
public interface PersonRespository extends PagingAndSortingRepository<Person, Integer> {
}
数据库部分构建完毕后,构建Service层,本文的Service层就直接写4个方法,对应CURD,源码如下:
package com.springBoot.curdDemo.service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springBoot.curdDemo.jpa.PersonRespository;
import com.springBoot.curdDemo.jpa.entity.Person;
@Service
public class PersonService {
@Autowired
PersonRespository personRespository;
public void create(String name, String phone) {
Person person = new Person();
person.setName(name);
person.setPhone(phone);
personRespository.save(person);
}
public void update(Integer id, String name, String phone) {
Person person = personRespository.findOne(id);
person.setName(name);
person.setPhone(phone);
personRespository.save(person);
}
public List read() {
List persons = new ArrayList();
Iterator it = personRespository.findAll().iterator();
while (it.hasNext()) {
Person person = it.next();
persons.add(person);
}
return persons;
}
public void delete(Integer id) {
personRespository.delete(id);
}
}