感兴趣的小伙伴可以加入QQ群:556029945
仓储部分开发
?和数据库交互,涉及到数据源的配置,为了小伙伴测试方便,这里采用H2数据库,以免有的小伙伴把代码写完了,却还要单独去安装如mysql,oracle的数据库,还要去写sql建表格,包括分享给他人都觉得不方便,以至于分外麻烦,这里我们就采用内存数据库,即启即用。
?1. 在pom中再次添加相关的依赖
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
</dependency>
?2. 通过/resource/applicantion.yml去配置数据源。
spring:
datasource:
type: org.springframework.jdbc.datasource.SimpleDriverDataSource
url: jdbc:h2:mem:personal_infos;MODE=Mysql;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
driver-class-name: org.h2.Driver
password: sa
username: sa
?3. 定义仓储接口与实现类
package com.dsh.rest.repository;
import com.dsh.rest.api.Profile;
public interface ProfileRepository {
String addProfile(Profile profile);
Profile query(String name);
}
package com.dsh.rest.repository.impl;
import com.dsh.rest.api.Contact;
import com.dsh.rest.api.Profile;
import com.dsh.rest.repository.ProfileRepository;
import com.dsh.rest.repository.entity.ProfilePO;
import com.dsh.rest.utils.Dates;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
@Repository
public class ProfileRepositoryImpl implements ProfileRepository {
private static final String TABLE_NAME = "PROFILE";
private static final String CULUMNS = "ID,NAME,AGE,BIRTHDAY,MARRIAGE_STATUS,PHONE_NUMBER,ADDRESS,INTRODUCTION,EMAIL,EMERGENCY_CONTACT,EMERGENCY_PHONE_NUMBER,EMERGENCY_ADDRESS";
private JdbcTemplate jdbcTemplate;
@Autowired
DataSource dataSource;
@Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
this.jdbcTemplate = jdbcTemplate;
jdbcTemplate.setDataSource(dataSource);
}
@Override
public String addProfile(Profile profile) {
String sql = "INSERT INTO " + TABLE_NAME + "("+CULUMNS+") VALUES (?,?,?"+",?,?,?"+",?,?,?,"+"?,?,?)";
double randomNum = Math.random() * 1000 * 1000;
String id = String.valueOf(Math.round(randomNum));
ProfilePO profilePO = getProfilePO(profile);
Object[] args = new Object[]{
id,
profilePO.getName(),
profilePO.getAge(),
profilePO.getBirthday(),
profilePO.getMarriageStatus(),
profilePO.getPhoneNumber(),
profilePO.getAddress(),
profilePO.getSelfIntroduction(),
profilePO.getEmail(),
profilePO.getEmergencyContact(),
profilePO.getEmergencyContactPhoneNumber(),
profilePO.getEmergencyContactAddress()
};
int[] types = new int[]{
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.DATE,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR
};
jdbcTemplate.update(sql,args,types);
return id;
}
@Override
public Profile query(String name) {
String sql = "SELECT * FROM " + TABLE_NAME+" WHERE NAME= ?";
Object[] args = new Object[]{
name,
};
int[] types = new int[]{
Types.VARCHAR,
};
List<Profile> profiles = jdbcTemplate.query(sql,args,types,new MyselfInfoRowMapper());
if (!profiles.isEmpty()){
return profiles.get(0);
}
return null;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
class MyselfInfoRowMapper implements RowMapper<Profile> {
@Override
public Profile mapRow(ResultSet resultSet, int i) throws SQLException {
Profile profile = new Profile();
profile.setId(resultSet.getString("ID"));
profile.setName(resultSet.getString("NAME"));
profile.setAge(resultSet.getString("AGE"));
Date birthday = resultSet.getDate("BIRTHDAY");
profile.setBirthday(Dates.dateToStr(birthday));
profile.setSelfIntroduction(resultSet.getString("INTRODUCTION"));
profile.setMarriageStatus(resultSet.getString("MARRIAGE_STATUS"));
Contact contact = new Contact();
contact.setPhoneNumber(resultSet.getString("PHONE_NUMBER"));
contact.setAddress(resultSet.getString("ADDRESS"));
contact.setEmail(resultSet.getString("EMAIL"));
contact.setEmergencyContact(resultSet.getString("EMERGENCY_CONTACT"));
contact.setEmergencyContactAddress(resultSet.getString("EMERGENCY_ADDRESS"));
contact.setEmergencyContactPhoneNumber(resultSet.getString("EMERGENCY_PHONE_NUMBER"));
profile.setContact(contact);
return profile;
}
}
private ProfilePO getProfilePO(Profile profile) {
ProfilePO profilePO = new ProfilePO();
profilePO.setName(profile.getName());
profilePO.setAge(profile.getAge());
profilePO.setBirthday(Dates.strToSimpleDate(profile.getBirthday()));
profilePO.setMarriageStatus(profile.getMarriageStatus());
profilePO.setSelfIntroduction(profile.getSelfIntroduction());
Contact contact = profile.getContact();
if (null != contact){
profilePO.setPhoneNumber(contact.getPhoneNumber());
profilePO.setAddress(contact.getAddress());
profilePO.setEmail(contact.getEmail());
profilePO.setEmergencyContact(contact.getEmergencyContact());
profilePO.setEmergencyContactPhoneNumber(contact.getEmergencyContactPhoneNumber());
profilePO.setEmergencyContactAddress(contact.getEmergencyContactAddress());
}
return profilePO;
}
}
?4. 存入数据库需要一个PO去转换一下
package com.dsh.rest.repository.entity;
import java.util.Date;
public class ProfilePO {
private String name;
private String age;
private Date birthday;
private String selfIntroduction;
private String marriageStatus;
private String phoneNumber;
private String address;
private String email;
private String emergencyContact;
private String emergencyContactPhoneNumber;
private String emergencyContactAddress;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSelfIntroduction() {
return selfIntroduction;
}
public void setSelfIntroduction(String selfIntroduction) {
this.selfIntroduction = selfIntroduction;
}
public String getMarriageStatus() {
return marriageStatus;
}
public void setMarriageStatus(String marriageStatus) {
this.marriageStatus = marriageStatus;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmergencyContact() {
return emergencyContact;
}
public void setEmergencyContact(String emergencyContact) {
this.emergencyContact = emergencyContact;
}
public String getEmergencyContactPhoneNumber() {
return emergencyContactPhoneNumber;
}
public void setEmergencyContactPhoneNumber(String emergencyContactPhoneNumber) {
this.emergencyContactPhoneNumber = emergencyContactPhoneNumber;
}
public String getEmergencyContactAddress() {
return emergencyContactAddress;
}
public void setEmergencyContactAddress(String emergencyContactAddress) {
this.emergencyContactAddress = emergencyContactAddress;
}
}
? 5. 配置DataSource
package com.dsh.rest.repository.configuration;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties({DataSourceProperties.class})
@ComponentScan(basePackageClasses = DataSourceConfig.class)
public class DataSourceConfig {
@Autowired
DataSourceProperties dataBaseProperties;
@Bean(destroyMethod = "close")
public DataSource dataSource(){
DataSourceBuilder dataSourceBuilder = DataSourceBuilder
.create()
.driverClassName(dataBaseProperties.getDriverClassName())
.url(dataBaseProperties.getUrl())
.username(dataBaseProperties.getUsername())
.password(dataBaseProperties.getPassword());
return dataSourceBuilder.build();
}
}
? 6. 提供一个工具类方法
public static String dateToStr(Date date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return simpleDateFormat.format(date);
}
? 7. 覆盖一下spring.factories,新建在/resource/META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.dsh.rest.repository.configuration.DataSourceConfig
?8. 在项目根目录下新建一个类如下:
package com.dsh.rest;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.google.common.collect.Lists;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.web.servlet.DispatcherServlet;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class,
DruidDataSourceAutoConfigure.class, QuartzAutoConfiguration.class})
public class BootApplication {
/* public static void main(String[] args) {
SpringApplication.run(BootApplication.class, args);
}
*/
private ApplicationContext applicationContext;
public void boot(String[] args) {
List<Resource> resources = Lists.newArrayList();
resources.add(new ClassPathResource("table.sql"));
applicationContext = SpringApplication.run(BootApplication.class, args);
DataSource dataSource = applicationContext.getBean(DataSource.class);
ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
populator.setScripts(resources.toArray(new ClassPathResource[]{}));
populator.execute(dataSource);
}
public static void main(String[] args) {
BootApplication appTest = new BootApplication();
appTest.boot(args);
}
@Bean
ServletWebServerFactory servletWebServerFactory() {
return new TomcatServletWebServerFactory();
}
@Bean
public ServletRegistrationBean regRestServlet(DispatcherServlet dispatcherServlet) {
ServletRegistrationBean registrationBean = new ServletRegistrationBean(dispatcherServlet);
registrationBean.addUrlMappings("/*");
return registrationBean;
}
}
原文地址:https://www.cnblogs.com/xixi0203/p/10647780.html
时间: 2024-10-11 23:51:19