`

SpringBoot实践 - SpringBoot+mysql

阅读更多

 

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;
    }
}
复制代码

 

  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>  

 

 

http://www.cnblogs.com/cnmenglang/p/6420940.html

分享到:
评论

相关推荐

    基于Springboot + Mybatis-Plus + echarts + Layui 的校园疫情防控系统源码.zip

    【标题】中的“基于Springboot + Mybatis-Plus + echarts + Layui 的校园疫情防控系统源码”揭示了这个项目采用的技术栈,主要用于构建一套校园疫情防控的后台管理系统。以下是这些技术的相关知识点: **Spring ...

    基于 SpringBoot + Mybatis Plus + Shiro + mysql + redis构建的智慧云智能教育平台

    SpringBoot + Mybatis Plus+ Shiro + mysql + redis + sharding-jdbc + canal构建的智慧云智能教育平台,基于数据驱动视图的理念封装 element-ui,即使没有 vue 的使用经验也能快速上手,提供 lambda 、stream api ...

    Springboot+MyBatis+mysql+jsp页面跳转详细示例.docx

    在本示例中,我们探讨的是如何使用...通过这样的实践,开发者可以深入理解SpringBoot的自动配置机制,MyBatis的简单操作数据库的能力,以及JSP页面在Web应用中的作用。同时,对于Maven项目管理也有了一定的了解。

    SpringBoot整合Mybatis-Plus+Oracle+Mysql

    本教程将深入探讨如何利用SpringBoot整合Mybatis-Plus,同时支持Oracle和MySQL数据库,并通过Nacos作为注册中心,以及使用Swagger2进行API文档的生成。 首先,让我们了解SpringBoot的核心优势。SpringBoot简化了...

    人工智能-项目实践-信息检索-基于SpringBoot+MyBaties+Thymeleaf+Elasticsearch开展的个

    SpringBoot做基础框架、SpringSecurity做授权与认证、Mybaties做数据访问层控制,全文检索使用Elasticsearch、数据库使用MySQL。 ElasticSearch 作为本站的站内搜索框架,支持分词检索数据和关键词高亮。 前台页面 ...

    springboot+mybatis-plus+gradle+mysql+swagger基础增删改查、树形查询

    本项目基于一系列技术栈,包括Spring Boot、MyBatis Plus、Gradle、MySQL和Swagger,实现了一个基础的增删改查(CRUD)功能,并提供了树形查询的能力。下面将详细介绍这些技术及其在项目中的应用。 **1. Spring ...

    tidb(mysql5.7) springboot mybatis-plus

    java Springboot开发必备环境 : 推荐1: 统一参数校验,自定义异常提醒,统一日志,统一响应返回,统一异常处理 。 推荐2: mybatis-plus 采用最新的生成代码工具 推荐3: 将多个基础功能整理后,并用单元测试验证...

    springboot-shiros-mybatis-redis+mysql(前后分离)

    【标题】"springboot-shiros-mybatis-redis+mysql(前后分离)"是一个基于Java的Web开发框架示例,它整合了Spring Boot、Shiro、MyBatis以及Redis和MySQL数据库,实现了前后端分离的设计模式。 【Spring Boot】是...

    基于springboot+mybatisplus+jsoup+mysql开发web小说网站

    总的来说,基于SpringBoot、MyBatisPlus、Jsoup和MySQL开发的Web小说网站,能够实现高效的数据管理、丰富的功能和良好的用户体验,是Java开发者在Web开发领域的一个典型实践案例。通过这个项目,开发者可以学习到...

    springboot+dubbo+nacos+mybatisplus+swagger+mysql

    【标题】"springboot+dubbo+nacos+mybatisplus+swagger+mysql" 是一个集成性的技术栈,用于构建高效、可扩展的企业级微服务应用。这个项目整合了多个流行的开源框架,包括Spring Boot、Dubbo、Nacos、MyBatis Plus、...

    Shiro + JWT + SpringBoot + MySQL + Redis(Jedis)实现无状态鉴权机制

    本项目结合了Apache Shiro、JSON Web Token (JWT)、SpringBoot、MySQL数据库以及Redis缓存技术(通过Jedis客户端)来实现这一机制。下面我们将详细探讨这些组件在实现无状态鉴权中的作用。 **Apache Shiro** Apache...

    springBoot+mysql+swagger练手demo.zip

    总结,"springBoot+mysql+swagger练手demo.zip"是一个理想的实践平台,它将带你走进SpringBoot的世界,体验MySQL的数据库操作,同时领略Swagger带来的API管理便利。无论你是初学者还是经验丰富的开发者,这个项目都...

    基于springboot+mybatis-plus+mysql的人力资源管理系统.zip

    《构建基于SpringBoot+Mybatis-Plus+MySQL的人力资源管理系统》 在现代企业中,人力资源管理系统的构建显得尤为重要,它能有效提升企业对员工信息、招聘、培训、考核等多方面管理的效率。本系统以SpringBoot为核心...

    毕设-基于springboot+mybatis+rabbitmp + mysql主题搜索的知识管理系统设计与实现.zip

    《基于SpringBoot+Mybatis+RabbitMQ+MySQL的主题搜索知识管理系统设计与实现》 本设计旨在构建一个高效、易用的知识管理系统,采用现代Web开发技术栈,包括SpringBoot、Mybatis、RabbitMQ和MySQL,以实现强大的主题...

    724便利店系统 springboot+mybatis-plus+thymeleaf+mysql+js

    【724便利店系统】是一个基于Java技术栈的项目,主要使用了SpringBoot、MyBatis-Plus、Thymeleaf、MySQL以及JavaScript等技术。这个项目的核心目标是提供一个全天候服务的便利店管理系统,方便进行商品管理、库存...

    Springboot+mybaits+mysql+redis+nginx,仓库管理系统。毕业设计

    "Springboot+mybaits+mysql+redis+nginx,仓库管理系统。毕业设计" 这个标题揭示了这个项目的核心技术栈和应用领域。它表明了一个基于Spring Boot框架的仓库管理系统,该系统集成了MyBatis作为持久层框架,MySQL作为...

    酒店客房 jiudiankefang-springboot+mybatis+jsp+mysql

    综上所述,"jiudiankefang"项目是一个全面的Java Web应用实践,涵盖了后端开发、数据库设计、前端展示等多个环节,对于学习和理解SpringBoot、Mybatis和JSP等技术有很好的参考价值。通过实际操作此项目,开发者可以...

    springboot+mybatis-plus+shiro

    4. 开发实践:开发者可以利用SpringBoot的starter快速引入依赖,使用Mybatis-Plus的API进行数据库操作,同时通过Shiro进行权限控制,例如,设置过滤器拦截特定URL,实现登录拦截和角色权限判断。 总结来说,...

    Java项目:电商书城平台系统设计和实现(java+springboot+mysql+spring+jsp)源码

    《电商书城平台系统设计与实现:基于Java+SpringBoot+MySQL+Spring+JSP的实战解析》 本文将深入探讨一个已经调试完成的电商书城平台系统,该系统采用Java编程语言,结合SpringBoot框架,配合MySQL数据库,以及...

Global site tag (gtag.js) - Google Analytics