1. 程式人生 > >springboot配置以及實現增刪改查

springboot配置以及實現增刪改查

1、配置

專案結構目錄

![在這裡插入圖片描述](https://img-blog.csdnimg.cn/20181031103409346.png

建立maven專案

在這裡插入圖片描述

maven配置檔案引入包

	<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.fanney<
/groupId> <artifactId>springboot</artifactId> <version>0.0.1-SNAPSHOT</version> <!-- 定義公共資源版本 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE
</version> <relativePath /> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <
/properties> <dependencies> <!-- 上邊引入 parent,因此 下邊無需指定版本 --> <!-- 包含 mvc,aop 等jar資源 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 熱部署 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <scope>true</scope> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency> <!-- 新增oracle jdbc driver <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> <version>10.2.0.5.0</version> </dependency> --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <!-- 沒有該配置,devtools 不生效 --> <fork>true</fork> </configuration> </plugin> </plugins> </build> </project>

配置application-test.properties(測試環境)

(開發環境和線上環境同下)

server.port=8089
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/school
spring.datasource.username=root
spring.datasource.password=0
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jackson.serialization.indent_output=true

#oracle
#custom.datasource.ds1.driver-class-name=oracle.jdbc.driver.OracleDriver
#custom.datasource.ds1.url=jdbc:oracle:thin:@localhost:1521:testdb
#custom.datasource.ds1.username=user
#custom.datasource.ds1.password=pass

配置application.properties(可切換環境)

spring.profiles.active=dev
#spring.profiles.active=test
#spring.profiles.active=prod

配置事務管理(以類的形式,以配置檔案形式可參考spring事務配置)

package com.fanney.springboot.framework;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;
import org.springframework.transaction.interceptor.RollbackRuleAttribute;
import org.springframework.transaction.interceptor.RuleBasedTransactionAttribute;
import org.springframework.transaction.interceptor.TransactionAttribute;
import org.springframework.transaction.interceptor.TransactionInterceptor;

//spring切面程式設計  把xml換成註解實現
@Aspect
@Configuration
public class TxAdviceInterceptor {
	private static final int TX_METHOD_TIMEOUT = 5;
	//兩個點的意思是中間夾層不管是啥名字都會匹配到
	private static final String AOP_POINTCUT_EXPRESSION = "execution (* com.fanney.springboot..service.*.*(..))";
	
	@Autowired
	private PlatformTransactionManager transactionManager;

	@Bean
	public TransactionInterceptor txAdvice() {
		NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
		
		// 只讀事務,不做更新操作
		RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
		readOnlyTx.setReadOnly(true);
		readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
		
		// 當前存在事務就使用當前事務,當前不存在事務就建立一個新的事務
		RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();
		requiredTx.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
		requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		requiredTx.setTimeout(TX_METHOD_TIMEOUT);
		
		Map<String, TransactionAttribute> txMap = new HashMap<String, TransactionAttribute>();
		txMap.put("add*", requiredTx);
		txMap.put("save*", requiredTx);
		txMap.put("insert*", requiredTx);
		txMap.put("update*", requiredTx);
		txMap.put("delete*", requiredTx);
		txMap.put("get*", readOnlyTx);
		txMap.put("query*", readOnlyTx);
		source.setNameMap(txMap);
		TransactionInterceptor txAdvice = new TransactionInterceptor(
				transactionManager, source);
		return txAdvice;
	}

	@Bean
	public Advisor txAdviceAdvisor() {
		AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
		pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
		return new DefaultPointcutAdvisor(pointcut, txAdvice());
	}

}

列印日誌(logback-spring.xml)

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- 檔案輸出格式 -->
    <property name="PATTERN" value="%-12(%d{yyyy-MM-dd HH:mm:ss.SSS}) |-%-5level [%thread] %c [%L] -| %msg%n" />
    <!-- test檔案路徑 -->
    <property name="TEST_FILE_PATH" value="d:/test.log" />
    <!-- pro檔案路徑 -->
    <property name="PRO_FILE_PATH" value="/opt/test/log" />
    
    <!-- 開發環境 -->
    <springProfile name="dev">
        <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
            <encoder>
                <pattern>${PATTERN}</pattern>
            </encoder>
        </appender>
        <logger name="com.fanney.springboot" level="debug" />
        <root level="info">
            <appender-ref ref="CONSOLE" />
        </root>
    </springProfile>
    
    <!-- 測試環境 -->
    <!-- springProfile 標籤的 name 屬性對應 application.properties 中的 spring.profiles.active 的配置。 -->
    <springProfile name="test">
        <!-- 每天產生一個檔案 -->
        <appender name="TEST-FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <!-- 檔案路徑 -->
            <file>${TEST_FILE_PATH}</file>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <!-- 檔名稱 -->
                <fileNamePattern>${TEST_FILE_PATH}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
                <!-- 檔案最大儲存歷史數量 -->
                <MaxHistory>100</MaxHistory>
            </rollingPolicy>
            <layout class="ch.qos.logback.classic.PatternLayout">
                <pattern>${PATTERN}</pattern>
            </layout>
        </appender>
        <root level="info">
            <appender-ref ref="TEST-FILE" />
        </root>
    </springProfile>
    
    <!-- 生產環境 -->
    <springProfile name="prod">
        <appender name="PROD_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <file>${PRO_FILE_PATH}</file>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <fileNamePattern>${PRO_FILE_PATH}/warn.%d{yyyy-MM-dd}.log</fileNamePattern>
                <MaxHistory>100</MaxHistory>
            </rollingPolicy>
            <layout class="ch.qos.logback.classic.PatternLayout">
                <pattern>${PATTERN}</pattern>
            </layout>
        </appender>
        <root level="warn">
            <appender-ref ref="PROD_FILE" />
        </root>
    </springProfile>
</configuration>

2、程式(以增刪改查為例)

程式啟動入口(SpringbootApplication)

package com.fanney.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootApplication {
	public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
}

實體類

package com.fanney.springboot.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

//注:jpa才需要的三個註解
@Entity
public class User {
	@Id
	@GeneratedValue
	private Long id;
	
	@Column(nullable=false)
	private String name;
 
	public Long getId() {
		return id;
	}
 
	public void setId(Long id) {
		this.id = id;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public User(String name) {
		super();
		this.name = name;
	}
 
	public User() {
		super();
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + "]";
	}

}

service層和serviceImpl實現層

package com.fanney.springboot.service;
import java.util.List;
import com.fanney.springboot.entity.User;

public interface UserService {
	//新增
	public User saveUser(User user);
	//刪除
	public void delete(Integer id);
	//修改
	public int update(Integer id,String name);
	//查詢所有
	List<User> findAll();
	//根據編號查詢
	User findOne(Integer id);
}	
package com.fanney.springboot.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fanney.springboot.dao.UserRespository;
import com.fanney.springboot.entity.User;
import com.fanney.springboot.service.UserService;

@Service
public class UserServiceImpl implements UserService{
	@Autowired
	private UserRespository UserRespository;
	
//	//用單獨事務的方法
//	//@Transactional(rollbackFor = { IllegalArgumentException.class })
//	//@Transactional(noRollbackFor = { IllegalArgumentException.class })
	public User saveUser(User user) {
		User result = UserRespository.save(user);//jpa自帶的新增方法
		if (result.getName().equals("sang")) {
			throw new IllegalArgumentException("sang已存在,資料將回滾");
		}
		return result;
	}
	
	public void delete(Integer id) {
		try {
			UserRespository.delete(id);//jpa自帶的新增方法
		} catch (Exception e) {
			throw new IllegalArgumentException("執行失敗,資料將回滾");
		}
	}
	
	public int update(Integer id,String name) {
		int result ;
		try {
			result = UserRespository.update(id,name);//jpa自帶的新增方法
		} catch (Exception e) {
			throw new IllegalArgumentException("執行失敗,資料將回滾");
		}
		return result;<