關於springBoot是個神馬東西以及優缺點,請自行搜索瞭解。java
LZ看到不少關於SpringBoot的Demo,單看一篇老是無法整合SpringBoot與Mysql。無法子,仍是本身操刀來一發爲妙。mysql
本文將敘述關於SpringBoot與mysql整合實踐。git
eclipse->help->Eclipse Marketplacegithub
b.檢測是否安裝成功web
安裝成功後提示重啓eclipse,重啓後新建Project 出現如圖redis
-->nextspring
-->next (選擇您須要的依賴,Finish後會在pom.xml中出現對應jar依賴) sql
-->Finishapache
項目結構以下:瀏覽器
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); } }
方式1:選擇項目->右鍵
方式2: eclipse->Windows->Show View
啓動成功後:
附加:
1.須要改動端口號:將resources下 application.properties 改成application.yml (我的愛好,可不改)
輸入
server: port: 9090 tomcat: uri-encoding: UTF-8
application.yml
server: port: 9090 tomcat: uri-encoding: UTF-8 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.0</modelVersion> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-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.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </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> <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.9</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=50,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(0).getName()); return result; } }
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); } }
<!-- springboot 熱部署 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional><!-- optional=true,依賴不會傳遞,該項目依賴devtools;以後依賴myboot項目的項目若是想要使用devtools,須要從新引入 --> </dependency>
至於如何訪問就不用過多介紹了吧。參照SpringMVC 便可。
後續將介紹 SpringBoot 實踐系列,敬請期待~~~