springboot整合mysql5.7_SpringBoot实践 - SpringBoot+mysql

关于springBoot是个神马东西以及优缺点,请自行搜索了解。

LZ看到很多关于SpringBoot的Demo,单看一篇总是没法整合SpringBoot与Mysql。没法子,还是自己操刀来一发为妙。

本文将叙述关于SpringBoot与mysql整合实践。

1.Eclipse 整合SpringBoot插件。(此步骤非常耗时,LZ本身尝试了多次。请在网络环境优情况下下进行操作)

a.Eclipse 安装STS插件:

eclipse->help->Eclipse Marketplace

b.检测是否安装成功

安装成功后提示重启eclipse,重启后新建Project 出现如图

2.新建SpringBoot Project

-->next

-->next (选择您需要的依赖,Finish后会在pom.xml中出现对应jar依赖)

-->Finish

项目结构如下:

package com.example;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;/**

* @ClassName: SpringBootDemoHelloApplication

* @Description:

* SpringBootDemoHelloApplication.java 是SpringBoot应用程序入口,或者叫主程序。

* 注解@SpringBootApplication 标注他是一个SpringBoot应用,main方法使他成为一个主程序,将在应用启动时首先被执行。

* 注解@RestController 标注这也是一个控制器。

* @author mengfanzhu

* @date 2017年2月20日 下午6:36:42*/@SpringBootApplication

@RestControllerpublic classSpringBootDemoHelloApplication {

@RequestMapping("/")publicString hello(){return "hello boot";

}public static voidmain(String[] args) {

SpringApplication.run(SpringBootDemoHelloApplication.class, args);

}

}

3.启动SpringBoot应用

方式1:选择项目->右键

方式2: eclipse->Windows->Show View

启动成功后:

附加:

1.需要改动端口号:将resources下 application.properties 改为application.yml (个人爱好,可不改)

输入

server:

port:9090tomcat:

uri-encoding: UTF-8

浏览器访问

3.代码结构

4.代码示例

application.yml

server:

port:9090tomcat:

uri-encoding: UTF-8spring:

datasource:

url: jdbc:mysql://localhost:3307/test?characterEncoding=UTF-8

username: test1

password: test1

driver-class-name: com.mysql.jdbc.Driver

jpa:

database: MYSQL

show-sql: truehibernate:

ddl-auto: update

naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy

properties:

hibernate:

dialect: org.hibernate.dialect.MySQL5Dialect

pom.xml

4.0.0

com.example

demo

0.0.1-SNAPSHOT

war

spring_boot_demo_hello

Demo project for Spring Boot

org.springframework.boot

spring-boot-starter-parent

1.5.1.RELEASE

UTF-8

UTF-8

1.8

org.springframework.boot

spring-boot-starter-aop

org.springframework.boot

spring-boot-starter-cache

org.springframework.boot

spring-boot-starter-data-redis

org.springframework.boot

spring-boot-starter-web

mysql

mysql-connector-java

runtime

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-starter-data-jpa

org.springframework.boot

spring-boot-starter-data-elasticsearch

com.sun.jna

jna

3.0.9

org.springframework.boot

spring-boot-starter-batch

org.springframework.boot

spring-boot-devtools

true

org.springframework.boot

spring-boot-maven-plugin

User.java

package com.example.entity;

import java.io.Serializable;

import java.util.Date;

import java.util.List;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.FetchType;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.JoinTable;

import javax.persistence.ManyToMany;

import javax.persistence.ManyToOne;

import javax.persistence.Table;

import org.springframework.format.annotation.DateTimeFormat;

import com.fasterxml.jackson.annotation.JsonBackReference;

@Entity

@Table(name="boot_user")public classUser implements Serializable {/**

* @Fields serialVersionUID : TODO*/

private static final long serialVersionUID = -6550777752269466791L;

@Id

@GeneratedValue(strategy=GenerationType.IDENTITY)privateLong id;

@Column(length=50,nullable=false)privateString name;privateString loginName;privateString password;

@DateTimeFormat(pattern= "yyyy-MM-dd HH:mm:ss")privateDate createdate;

@ManyToOne

@JoinColumn(name= "did")

@JsonBackReferenceprivateDepartment department;

@ManyToMany(cascade={},fetch =FetchType.EAGER)

@JoinTable(name= "user_role",

joinColumns={@JoinColumn(name="user_id")},

inverseJoinColumns= {@JoinColumn(name="roles_id")})private ListroleList;publicLong getId() {returnid;

}public voidsetId(Long id) {this.id =id;

}publicString getName() {returnname;

}public voidsetName(String name) {this.name =name;

}publicDate getCreatedate() {returncreatedate;

}public voidsetCreatedate(Date createdate) {this.createdate =createdate;

}publicString getLoginName() {returnloginName;

}public voidsetLoginName(String loginName) {this.loginName =loginName;

}publicString getPassword() {returnpassword;

}public voidsetPassword(String password) {this.password =password;

}publicDepartment getDepartment() {returndepartment;

}public voidsetDepartment(Department department) {this.department =department;

}public ListgetRoleList() {returnroleList;

}public void setRoleList(ListroleList) {this.roleList =roleList;

}publicUser() {

super();//TODO Auto-generated constructor stub

}publicUser(Long id, String name, String loginName, String password,

Date createdate, Department department, ListroleList) {

super();this.id =id;this.name =name;this.loginName =loginName;this.password =password;this.createdate =createdate;this.department =department;this.roleList =roleList;

}

}

Department.java,Role.java 代码参照User.java代码即可

UserDao.java

package com.example.dao;

import java.util.Date;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.stereotype.Repository;

import com.example.entity.User;

@Repositorypublic interface UserDao extends JpaRepository{

User findByLoginNameLike(String name);

User readByLoginName(String name);

ListgetByCreatedateLessThan(Date star);

}

DepartmentDao.java,RoleDao.java参考UserDao.java 即可,这样就实现了分页、增删改查等功能。很便捷有木有!那为什么呢?看下JpaRepository接口,方法命名规则及相关问题后续重点介绍.

UserController.java

package com.example.controller;

import java.util.HashMap;

import java.util.Map;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.util.Assert;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.bind.annotation.RestController;

import com.example.entity.User;

import com.example.service.DataService;

import com.example.service.UserService;/**

* @ClassName: UserController

* @Description: User控制器

* @author mengfanzhu

* @date 2017年2月20日 下午5:58:19*/@RestController

@RequestMapping("/user")public classUserController {protected static Logger logger=LoggerFactory.getLogger(UserController.class);

@AutowiredprivateUserService userService;

@AutowiredprivateDataService dataService;

@RequestMapping("/demo/{name}")

@ResponseBodypublicString demoShowName(@PathVariable String name){

logger.debug("访问getUserByName,Name={}",name);return "name is" +name;

}/**

* @Title: UserController

* @Description: 数据初始化

* @author mengfanzhu

* @throws*/@RequestMapping("/initdata")

@ResponseBodypublicString initData(){

dataService.initData();return "success";

}/**

* @Title: UserController

* @Description: 由loginName获取user

* @param loginName

* @author mengfanzhu

* @throws*/@RequestMapping("/getUserByLoginName/{loginName}")

@ResponseBodypublic MapgetUserByName(@PathVariable String loginName){

Map result = new HashMap();

User user=userService.readByLoginName(loginName);

Assert.notNull(user);

result.put("name", user.getName());

result.put("loginName", user.getLoginName());

result.put("departmentName",user.getDepartment().getName());

result.put("roleName", user.getRoleList().get(0).getName());returnresult;

}

}

JpaConfiguration.java

package com.example;

import org.springframework.boot.autoconfigure.domain.EntityScan;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.core.Ordered;

import org.springframework.core.annotation.Order;

import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;

import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import org.springframework.transaction.annotation.EnableTransactionManagement;/**

* @ClassName: JpaConfiguration

* @Description: Jpa的配置类。

* @EnableTransactionManagement 启用了JPA 的事务管理

* @EnableJpaRepositories 启用了JPA资源库并指定了上面定义的接口资源库的位置

* @EntityScan 指定了定义实体的位置

* @author mengfanzhu

* @date 2017年2月20日 下午7:21:39*/@Order(Ordered.HIGHEST_PRECEDENCE)

@Configuration

@EnableTransactionManagement(proxyTargetClass= true)

@EnableJpaRepositories(basePackages= "com.example.dao")

@EntityScan(basePackages= "com.example.entity")public classJpaConfiguration {

@Bean

PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor(){return newPersistenceExceptionTranslationPostProcessor();

}

}

DataServiceImpl.java

package com.example.service;

import java.util.Date;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.util.Assert;

import com.example.dao.DepartmentDao;

import com.example.dao.RoleDao;

import com.example.dao.UserDao;

import com.example.entity.Department;

import com.example.entity.Role;

import com.example.entity.User;

@Servicepublic classDataServiceImpl implements DataService{

@AutowiredprivateUserDao userDao;

@AutowiredprivateRoleDao roleDao;

@AutowiredprivateDepartmentDao departmentDao;public voidinitData(){

userDao.deleteAll();

departmentDao.deleteAll();

roleDao.deleteAll();

Department department= newDepartment();

department.setName("财务部");

department.setCreatedate(newDate());

departmentDao.save(department);

Assert.notNull(department.getId(),"部门ID不能为空!");

Role role= newRole();

role.setName("管理员");

role.setCreatedate(newDate());

roleDao.save(role);

Assert.notNull(role.getId(),"角色ID不能为空");

User user= newUser();

user.setName("管理员");

user.setLoginName("admin");

user.setDepartment(department);

List roleList =roleDao.findAll();

Assert.notNull(roleList,"角色列表不能为空!");

user.setRoleList(roleList);

user.setPassword("admin");

userDao.save(user);

Assert.notNull(user.getId(),"用户ID不能为空!");

}

}

UserServiceImpl.java

package com.example.service;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import com.example.dao.UserDao;

import com.example.entity.User;

@Servicepublic classUserServiceImpl implements UserService {

@AutowiredprivateUserDao userDao;

@OverridepublicUser readByLoginName(String name) {returnuserDao.readByLoginName(name);

}

}

5.运行+SpringBoot热部署

org.springframework.boot

spring-boot-devtools

true

至于如何访问就不用过多介绍了吧。参照SpringMVC 即可。

后续将介绍 SpringBoot 实践系列,敬请期待~~~

你可能感兴趣的:(springboot整合mysql5.7_SpringBoot实践 - SpringBoot+mysql)