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
@RestController
public class SpringBootDemoHelloApplication { @RequestMapping("/")
public String hello(){
return "hello boot";
} public static void main(String[] args) {
SpringApplication.run(SpringBootDemoHelloApplication.class, args);
}
}
3.启动SpringBoot应用
方式1:选择项目->右键
方式2: eclipse->Windows->Show View
启动成功后:
附加:
1.需要改动端口号:将resources下 application.properties 改为application.yml (个人爱好,可不改)
输入
server:
port:
tomcat:
uri-encoding: UTF-
浏览器访问
3.代码结构
4.代码示例
application.yml
server:
port:
tomcat:
uri-encoding: UTF- spring:
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: true
hibernate:
ddl-auto: update
naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.</modelVersion> <groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.-SNAPSHOT</version>
<packaging>war</packaging> <name>spring_boot_demo_hello</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5..RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>
spring-boot-starter-data-elasticsearch
</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.jna/jna -->
<dependency>
<groupId>com.sun.jna</groupId>
<artifactId>jna</artifactId>
<version>3.0.</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-batch -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<!-- springboot 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional><!-- optional=true,依赖不会传递,该项目依赖devtools;之后依赖myboot项目的项目如果想要使用devtools,需要重新引入 -->
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
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 class User implements Serializable { /**
* @Fields serialVersionUID : TODO
*/
private static final long serialVersionUID = -6550777752269466791L; @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; @Column(length=,nullable=false)
private String name; private String loginName; private String password; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createdate; @ManyToOne
@JoinColumn(name = "did")
@JsonBackReference
private Department department; @ManyToMany(cascade={},fetch = FetchType.EAGER)
@JoinTable(name = "user_role",
joinColumns={@JoinColumn(name="user_id")},
inverseJoinColumns = {@JoinColumn(name="roles_id")})
private List<Role> roleList; 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 Date getCreatedate() {
return createdate;
} public void setCreatedate(Date createdate) {
this.createdate = createdate;
} public String getLoginName() {
return loginName;
} public void setLoginName(String loginName) {
this.loginName = loginName;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public Department getDepartment() {
return department;
} public void setDepartment(Department department) {
this.department = department;
} public List<Role> getRoleList() {
return roleList;
} public void setRoleList(List<Role> roleList) {
this.roleList = roleList;
} public User() {
super();
// TODO Auto-generated constructor stub
} public User(Long id, String name, String loginName, String password,
Date createdate, Department department, List<Role> roleList) {
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;
@Repository
public interface UserDao extends JpaRepository<User, Long> { User findByLoginNameLike(String name); User readByLoginName(String name); List<User> getByCreatedateLessThan(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 class UserController { protected static Logger logger=LoggerFactory.getLogger(UserController.class);
@Autowired
private UserService userService;
@Autowired
private DataService dataService; @RequestMapping("/demo/{name}")
@ResponseBody
public String demoShowName(@PathVariable String name){
logger.debug("访问getUserByName,Name={}",name);
return "name is " + name;
}
/**
* @Title: UserController
* @Description: 数据初始化
* @author mengfanzhu
* @throws
*/
@RequestMapping("/initdata")
@ResponseBody
public String initData(){
dataService.initData();
return "success";
} /**
* @Title: UserController
* @Description: 由loginName获取user
* @param loginName
* @author mengfanzhu
* @throws
*/
@RequestMapping("/getUserByLoginName/{loginName}")
@ResponseBody
public Map<String,Object> getUserByName(@PathVariable String loginName){
Map<String,Object> result = new HashMap<String, Object>();
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().getName());
return result;
}
}
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 class JpaConfiguration { @Bean
PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor(){
return new PersistenceExceptionTranslationPostProcessor();
}
}
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; @Service
public class DataServiceImpl implements DataService{ @Autowired
private UserDao userDao;
@Autowired
private RoleDao roleDao;
@Autowired
private DepartmentDao departmentDao; public void initData(){
userDao.deleteAll();
departmentDao.deleteAll();
roleDao.deleteAll(); Department department = new Department();
department.setName("财务部");
department.setCreatedate(new Date()); departmentDao.save(department);
Assert.notNull(department.getId(),"部门ID不能为空!"); Role role = new Role();
role.setName("管理员");
role.setCreatedate(new Date()); roleDao.save(role);
Assert.notNull(role.getId(),"角色ID不能为空"); User user = new User();
user.setName("管理员");
user.setLoginName("admin");
user.setDepartment(department);
List<Role> 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; @Service
public class UserServiceImpl implements UserService { @Autowired
private UserDao userDao;
@Override
public User readByLoginName(String name) {
return userDao.readByLoginName(name);
} }
5.运行+SpringBoot热部署
<!-- springboot 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional><!-- optional=true,依赖不会传递,该项目依赖devtools;之后依赖myboot项目的项目如果想要使用devtools,需要重新引入 -->
</dependency>
至于如何访问就不用过多介绍了吧。参照SpringMVC 即可。
代码已上传至 Github ,https://github.com/fzmeng/spring_boot_demo_hello
后续将介绍 SpringBoot 实践系列,敬请期待~~~
SpringBoot实践 - SpringBoot+mysql的更多相关文章
- SpringBoot实践 - SpringBoot+MySql+Redis
大家都知道redis的强大之处,在目前应用上也是大显神威. 先说说他的优点: 1 读写性能优异 2 支持数据持久化,支持AOF日志和RDB快照两种持久化方式 3 支持主从复制,主机会自动将数据同步到从 ...
- Springboot+Atomikos+Jpa+Mysql实现JTA分布式事务
1 前言 之前整理了一个spring+jotm实现的分布式事务实现,但是听说spring3.X后不再支持jotm了,jotm也有好几年没更新了,所以今天整理springboot+Atomikos+jp ...
- Java逆向工程SpringBoot + Mybatis Generator + MySQL
Java逆向工程SpringBoot+ Mybatis Generator + MySQL Meven pop.xml文件添加引用: <dependency> <groupId> ...
- Springboot集成mybatis(mysql),mail,mongodb,cassandra,scheduler,redis,kafka,shiro,websocket
https://blog.csdn.net/a123demi/article/details/78234023 : Springboot集成mybatis(mysql),mail,mongodb,c ...
- SpringBoot 使用JPA+MySQL+Thymeleaf 总结 二
SpringBoot 使用JPA+MySQL+Thymeleaf 总结 一 SpringBoot 使用JPA+MySQL+Thymeleaf 总结 二 方法一 使用原生sql查询 或者 为方法名增加 ...
- SpringBoot 使用JPA+MySQL+Thymeleaf 总结 一
SpringBoot 使用JPA+MySQL+Thymeleaf 总结 一 SpringBoot 使用JPA+MySQL+Thymeleaf 总结 二 pom引用 <?xml version=& ...
- SpringBoot(七)-SpringBoot JPA-Hibernate
步骤 1.在pom.xml添加mysql,spring-data-jpa依赖2.在application.properties文件中配置mysql连接配置文件3.在application.proper ...
- 【SpringBoot】SpringBoot 入门示例
参考资料: http://www.tuicool.com/articles/mqeee2A http://www.cnblogs.com/suncj/p/4065589.html http://spr ...
- springBoot系列-->springBoot注解大全
一.注解(annotations)列表 @SpringBootApplication:包含了@ComponentScan.@Configuration和@EnableAutoConfiguration ...
随机推荐
- Linux怎样访问Windows共享文件和文件夹
常常使用Windows的人可能会发现,Windows计算机之前共享资料非常方便,但是有时候想玩玩Linux的时候,如Fedora.Ubuntu.CentOS等,该怎样才能访问Windows计算机上的文 ...
- 获取IIS版本
近日,有一项目要分别获取iis6.0和7.5,然后对进程进行操作~ 研究良久,有以下办法获取iis版本. 代码: DirectoryEntry getEntity = new DirectoryEnt ...
- [Angular Tutorial] 5-Filtering Repeaters
在上一步中,我们花了很大功夫来布局应用的基础,所以我们现在做点简单点的吧!我们将会添加一个全文本搜索框(没错,这很简单). ·我们的应用现在会有一个搜索框,注意页面中手机列表的改变取决于用户在搜索框键 ...
- java系列--HTTP协议
一.HTTP请求信息 请求行 请求头 空行 消息体 1.防盗链: 枚举类型: 二.中文乱码问题 1.Get提交 String username = request.getParameter(" ...
- SpringMVC常用注解@Controller,@Service,@repository,@Component
SpringMVC常用注解@Controller,@Service,@repository,@Component controller层使用@controller注解 @Controller 用于标记 ...
- 笔记整理——C语言-http-1
http 传输原理及格式 - friping - ITeye技术网站 - Google Chrome (2013/4/1 14:02:36) http 传输原理及格式 博客分类: 其他 应用服务器浏览 ...
- 堡垒机--paramiko模块
做堡垒机之前,来了解一下paramiko模块. 实际上底层封装的SSH. SSHclient(1) import paramiko #实例化一个ssh ssh = paramiko.SSHClient ...
- 得到css style
//根据ID返回dom元素 2 var $ = function(id){return document.getElementById(id);} 3 //返回dom元素的当前某css值 4 var ...
- ID3算法(Java实现)
数据存储文件:buycomputer.properties #数据个数 datanum=14 #属性及属性值 nodeAndAttribute=年龄:青/中/老,收入:高/中/低,学生:是/否,信誉: ...
- zepto.js 处理Touch事件
处 理Touch事件能让你了解到用户的每一根手指的位置,在touch事件触发的时候产生,可以通过touch event handler的event对象取到,如果基于zepto.js开发,一般是通过ev ...