zoukankan      html  css  js  c++  java
  • spring-boot 代码示例2 mysql

    &代表在后台运行
    nohup 意思是不挂断运行命令,当账户退出或终端关闭时,程序仍然运行
    
    nohup java -jar sam-service-mongo-0.0.1.jar -server -Xms256m -Xmx1024m -Xss256k > ./run.log 2>&1 &
    nohup java -jar sam-service-mongo-0.0.1.jar  > ./run.log 2>&1 &
    
    http://localhost:16031/test/hello
    
    执行顺序
    @RestController-->@Service-->interface
    
    ---------------------------------------------------------------------------------------------------------------------------
    import org.springframework.beans.BeanUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @author fenglei.ma 2017/12/21 17:21
     */
    @RestController
    @RequestMapping("/dict/entity")
    public class DictEntityController extends BaseController {
    
        private static final Logger logger = Logger.getLogger(DictEntityController.class);
    
        @Autowired
        private DictEntityService dictEntityService;
    
        /** 保存 */
        @RequestMapping(value = "/save", method = RequestMethod.POST)
        public RespObj save(DictEntity entity) {
            logger.info("param -> entity" + entity);
            dictEntityService.save(entity);
            return build();
        }
    
        /** 删除 */
        @RequestMapping(value = "/remove", method = RequestMethod.POST)
        public RespObj remove(Long id) {
            logger.info("param -> id :" + id);
            dictEntityService.remove(id);
            return build();
        }
    
        /** 列表 */
        @RequestMapping(value = "/list", method = RequestMethod.POST)
        public RespObj list(RequestVO vo) {
            logger.info(vo.toString());
            if (vo.getPage() == null) {
                vo.setPage(0);
            }
            if (vo.getPage() < 0) {
                vo.setPage(0);
            }
    
            if (vo.getSize() == null) {
                vo.setSize(10);
            }
    
            return build(dictEntityService.findByEntityWithPage(vo));
        }
    
        @RequestMapping(value = "getall", method = RequestMethod.POST)
        public RespObj getAll(RequestVO param) {
            logger.info("param ->" + param.toString());
            if (param.getPage() == null) {
                param.setPage(0);
            }
            if (param.getPage() < 0) {
                param.setPage(0);
            }
    
            if (param.getSize() == null) {
                param.setSize(10);
            }
            return build(dictEntityService.getAll(param));
        }
    
        /** 修改 */
        @RequestMapping(value = "update", method = RequestMethod.POST)
        public RespObj update(Long id, String name, String word, Integer type) {
            logger.info("param --> id :" + id + ",name :" + name + ",type:" + type);
            dictEntityService.update(id, name, word, type);
            return build();
        }
    
        /** 根据 name 和 word 查询  */
        @RequestMapping(value = "/find/nameword", method = RequestMethod.POST)
        public RespObj findByNameAanWordZ(RequestVO param) {
            logger.info("param ->" + param);
            DictEntity entity = new DictEntity();
            BeanUtils.copyProperties(param, entity);
            List<DictEntity> result = dictEntityService.findByNameAndWord(entity);
            return build(result);
        }
    
        /** 根据 ids查询  */
        @RequestMapping(value = "/find/ids", method = RequestMethod.POST)
        public RespObj findByNameAanWordZ(String ids) {
            logger.info("param -> ids" + ids);
    
            // Strings.isNullOrEmpty(o)
            List<Long> parseIds = Arrays.asList(ids.split(",")).stream()
                    .map((t) -> Long.valueOf(t)).filter((o) -> !Objects.isNull(o)).collect(Collectors.toList());
    
            List<DictEntity> result = dictEntityService.findByIdIn(parseIds);
    
            return build(result);
        }
    
    
    }
    
    ---------------------------------------------------------------------------------------------------------------------------
    import javax.persistence.criteria.CriteriaBuilder;
    import javax.persistence.criteria.CriteriaQuery;
    import javax.persistence.criteria.Predicate;
    import javax.persistence.criteria.Root;
    import org.apache.commons.lang.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.domain.Page;
    import org.springframework.data.domain.PageRequest;
    import org.springframework.data.domain.Pageable;
    import org.springframework.data.domain.Sort;
    import org.springframework.data.domain.Sort.Direction;
    import org.springframework.data.jpa.domain.Specification;
    import org.springframework.stereotype.Service;
    
    /**
     * @author fenglei.ma 2017/12/21 16:52
     */
    @Service
    public class DictEntityService {
    
        @Autowired
        private DictEntityDao dictEntityDao;
    
        public void save(DictEntity entity) {
            dictEntityDao.save(entity);
        }  
        public List<DictEntity> findByNameAndWord(DictEntity entity){
            return dictEntityDao.findByNameAndWord(entity.getName(), entity.getWord());
        }
        public List<DictEntity> findByIdIn(List<Long> ids){
            return dictEntityDao.findByIdIn(ids);
        }
        public void remove(Long id) {
            dictEntityDao.updateState(id, WordConstants.STATE_1);
    //      dictEntityDao.delete(id);
        }
    
        public PageDto<DictEntity> findByEntityWithPage(RequestVO vo) {
            Specification<DictEntity> specification = new Specification<DictEntity>() {
                @Override
                public Predicate toPredicate(Root<DictEntity> root,
                        CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                    List<Predicate> list = new ArrayList<Predicate>(); 
                    if(StringUtils.isNotBlank(vo.getName())) {
                        list.add(criteriaBuilder.like(root.get("name").as(String.class), "%"+vo.getName()+"%"));
                    }
                    if(vo.getType() != null) {
                        list.add(criteriaBuilder.equal(root.get("type").as(Integer.class), vo.getType()));
                    }
                    list.add(criteriaBuilder.equal(root.get("state").as(Integer.class), WordConstants.STATE_2));
                    
                    Predicate[] p = new Predicate[list.size()];
                    
                    return criteriaBuilder.and(list.toArray(p));
                }
                
            };
            
            Sort sort = new Sort(Direction.DESC, "id");
            Pageable pageable = new PageRequest(vo.getPage(), vo.getSize(), sort);
            
            Page<DictEntity> pageResult = dictEntityDao.findAll(specification, pageable);
            
            return new PageDto<>(pageResult.getTotalElements(), pageResult.getContent());
        }
        
         public PageDto<DictEntity> getAll(RequestVO vo){
             Specification<DictEntity> specification = new Specification<DictEntity>() {
                    @Override
                    public Predicate toPredicate(Root<DictEntity> root, CriteriaQuery<?> query,
                            CriteriaBuilder cb) {
                        query.orderBy(cb.desc(root.get("crt").as(Date.class)));
                        return query.getRestriction();
                    }
                };
                
            Page<DictEntity> findAll = dictEntityDao.findAll(specification,  new PageRequest(vo.getPage(), vo.getSize()));       
            return new PageDto<>(findAll.getTotalElements(), findAll.getContent());
         }
         
         public void update(Long id, String name, String word, Integer type){
             dictEntityDao.update(id, name, word, type);
         }
    }
    ------------------------------------------------------------------------
    package com.csf.study.service;
    
    import com.csf.study.domain.dao.DictEntityDao;
    import com.csf.study.domain.entity.DictEntity;
    import org.apache.log4j.Logger;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.BeanPropertyRowMapper;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.core.RowMapper;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.Date;
    import java.util.List;
    
    /**
     * Created by fenglei.ma on 2018/4/23. 15:10
     * jdbcTemplate 使用
     */
    @Service
    public class EntityService {
    
        private static final Logger logger = Logger.getLogger(EntityService.class);
    
        @Autowired
        private DictEntityDao dictEntityDao;
    
        // 使用spring 的 jdbcTemplate 进行查询
        @Autowired
        private JdbcTemplate jdbcTemplate;
    
        // 使用jdbcTemplate 查询 自动将sql转化为对应的实体类
        public List<DictEntity> findAll() {
            String sql = "select * from dict_xiaoma f where  1=1 ";
            List<DictEntity> dataList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(DictEntity.class));
            return dataList;
        }
    
        public List<DictEntity> getEntityList() {
            String sql = "select * from dict_xiaoma f where  1=1 ";
            return jdbcTemplate.query(sql, new RowMapper<DictEntity>() {
                @Override
                public DictEntity mapRow(ResultSet rs, int rowNum) throws SQLException {
                    DictEntity entity = new DictEntity();
                    entity.setName(rs.getString("name"));
                    entity.setWord(rs.getString("word"));
                    entity.setCrt(rs.getDate("crt"));
                    entity.setCru(rs.getString("cru"));
                    entity.setState(rs.getInt("state"));
                    entity.setType(rs.getInt("type"));
                    entity.setUpt(rs.getDate("upt"));
                    return entity;
                }
            });
        }
    
        @Transactional
        public void insertEntity() {
            Long maxId = dictEntityDao.findMaxId();
            String sql = "insert into dict_xiaoma(id,name,word,state,type,crt,upu,upt) values(?,?,?,?,?,?,?,?)";
            int  numrow= jdbcTemplate.update(sql, new Object[]{maxId + 1, "吴欢", "wuhuan123", 2, 2, new Date(), "SO4793471", new Date()});
            logger.info(" 添加成功 " + numrow + " 条数据");
        }
    
        @Transactional
        public void update() {
            String sql = "update dict_xiaoma set name = ? , lastmodified_by = ?  where id = ? ";
            int  numrow= jdbcTemplate.update(sql, new Object[]{"新上古" ,"EF7114-A485522-B111", 8});
            logger.info(numrow + " 条数据 修改成功");
        }
    
    
    }
    
    
    ---------------------------------------------------------------------------------------------------------------------------
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
    import org.springframework.data.jpa.repository.Modifying;
    import org.springframework.data.jpa.repository.Query;
    import org.springframework.data.repository.query.Param;
    import org.springframework.transaction.annotation.Transactional;
    import org.springframework.data.jpa.repository.Query;
    
    /**
     * @author fenglei.ma 2017/12/21 16:49
     */
    public interface DictEntityDao extends JpaRepository<DictEntity, Long>,
            JpaSpecificationExecutor<DictEntity> {
    
        @Modifying
        @Transactional
        @Query("update DictEntity u set u.state = :state where u.id = :id")
        int updateState(@Param("id") Long id, @Param("state") Integer state);
        
        @Modifying
        @Transactional
        @Query("update DictEntity u set u.name = :name, u.word = :word, u.type = :type where u.id = :id")
        int update(@Param("id") Long id, @Param("name") String name, @Param("word") String word, @Param("type") Integer type);
        
        // 根据字段自动映射  根据name查询
        List<DictEntity> findByName(String name);
    
        // 根据 name 和 word 查询
        List<DictEntity> findByNameAndWord(String name, String word);
    
        List<DictEntity> findByIdIn(List<Long> ids);
    
        @Query("select max(id) from DictEntity")
        Long findMaxId();
    
    }
    ---------------------------------------------------------------------------------------------------------------------------
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import com.fasterxml.jackson.annotation.JsonFormat;
    import com.fasterxml.jackson.annotation.JsonIgnore;
    import com.fasterxml.jackson.annotation.JsonInclude;
    
    /**
     * @author fenglei.ma 2017/12/21 16:36
     * mysql 版本实体类
     */
    @Entity // 实体类的注解
    @Table(name = "dict_xiaoma")
    public class DictEntity implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        // 自增主键
        @Id // 映射到表格中id的属性
        @GeneratedValue // 自增的属性
        private Long id;
        private String name;
        private String word;
        private Integer type;
        private Integer state;
        private String cru;
        private String upu;
        
        @Column(name = "lastmodified_by") // 将字段设置为 lastmodified_by
        @JsonIgnore  // json序列化时字段被忽视
    //  @CreatedBy
        private String lastmodifiedBy;
        
        @Column(insertable = true) // true 为 insert sql 时进行插入
        @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    //  @CreatedDate
        private Date crt;
    
        @Column(insertable = true)
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") // 指明时间存储格式
    //  @LastModifiedDate
        private Date upt;
    
    }
    ---------------------------------------------------------------------------------------------------------------------------
    
    /**
     * @author fenglei.ma  分页封装
     */
    public class PageDto<T> {
    
        private Long total;
        private List<T> result;
    
        public PageDto(Long total, List<T> result) {
            this.total = total;
            this.result = result;
        }
    }
    
    ---------------------------------------------------------------------------------------------------------------------------
    
    配置文件信息 application.properties
        # 端口
        server.port=16031
        path.upload=/usr/loc/upload
    
        # msyql配置
        spring.datasource.driver-class-name=com.mysql.jdbc.Driver
        spring.datasource.url=jdbc:mysql://192.168.250.208:3306/pandora
        spring.datasource.username=ada_user
        spring.datasource.password=ada_user
    
        #spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop
        # 是否打开验证
        management.security.enabled=false
    
        # 是否打印出自动生产的SQL
        spring.jpa.show-sql=true
    
        # 项目启动是否根据实体类生成表格
        spring.jpa.hibernate.ddl-auto=update
        spring.jpa.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
        spring.jackson.serialization.indent_output=false
    
    ---------------------------------------------------------------------------------------------------------------------------
    日志配置信息 log4j.properties
    
        log4j.rootLogger=DEBUG,Console,LogFile,ErrorFile
    
        # Console appender #
        log4j.appender.Console=org.apache.log4j.ConsoleAppender
        log4j.appender.Console.Threshold=INFO
        log4j.appender.Console.Target=System.out
        log4j.appender.Console.layout=org.apache.log4j.PatternLayout
        log4j.appender.Console.layout.ConversionPattern=%d{ISO8601} %5p %c{1}:%L - %m%n
    
        # Save the log info to the log file #
        log4j.appender.LogFile=org.apache.log4j.DailyRollingFileAppender
        log4j.appender.LogFile.File=/app/log/spring-boot-stuty/pring-boot-stuty.log
        log4j.appender.LogFile.Append=true
        log4j.appender.LogFile.Threshold=INFO
        log4j.appender.LogFile.layout=org.apache.log4j.PatternLayout
        log4j.appender.LogFile.layout.ConversionPattern=%d{ISO8601} %5p %c{1}:%L - %m%n
    
        # Save the log error to the log file #
        log4j.appender.ErrorFile=org.apache.log4j.DailyRollingFileAppender
        log4j.appender.ErrorFile.File=/app/log/pring-boot-stuty/pring-boot-stuty_error.log
        log4j.appender.ErrorFile.Append=true
        log4j.appender.ErrorFile.Threshold=ERROR
        log4j.appender.ErrorFile.layout=org.apache.log4j.PatternLayout
        log4j.appender.ErrorFile.layout.ConversionPattern=%d{ISO8601} %5p %c{1}:%L - %m%n
    
    ---------------------------------------------------------------------------------------------------------------------------
    pom配置文件 pom.xml
    
    <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.csf</groupId>
        <artifactId>spring-boot-study</artifactId>
        <version>0.0.1</version>
        <packaging>jar</packaging>
    
        <name>spring-boot-study</name>
        <url>http://www.ityouknow.com/</url>
        <description>Demo project for Spring Boot</description>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.9.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>
            <starter.log4j.version>1.3.8.RELEASE</starter.log4j.version>
            <guava.version>20.0</guava.version>
        </properties>
    
        <dependencies>
    
            <!-- 核心模块 包括自动配置支持、日志和yaml -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
                <exclusions>
                    <exclusion>
                        <!-- 排除spring boot对[spring-boot-starter-logging]的依赖,并增加依赖包[spring-boot-starter-log4j.jar] -->
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-logging</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
    
            <!-- web模块 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <!-- 测试模块 包括JUnit、Hamcrest、Mockito -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <!-- jpa模块 数据持久化 利用Hibernate生成各种自动化的sql -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
    
            <!-- mysql驱动 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
    
            <!-- 开发环境的调试 热启动 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <optional>true</optional>
            </dependency>
    
            <!-- 实体数据库表映射 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
    
            <dependency>
                <groupId>commons-lang</groupId>
                <artifactId>commons-lang</artifactId>
                <version>2.6</version>
            </dependency>
    
            <!-- 日志模块 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-log4j</artifactId>
                <version>${starter.log4j.version}</version>
            </dependency>
    
            <dependency>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
                <version>${guava.version}</version>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <configuration>
                        <!--//热启动 该配置必须-->
                        <fork>true</fork>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>
    ---------------------------------------------------------------------------------------------------------------------------
    启动类
    
    package com.csf.study;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    /**
     * @author fenglei.ma 2017/12/21 15:15
     */
    @SpringBootApplication
    public class StudyApplication {
        
        public static void main(String[] args) {
            SpringApplication.run(StudyApplication.class, args);
        }
    }
    ---------------------------------------------------------------------------------------------------------------------------
    package com.csf.study.web;
    
    import com.csf.study.domain.dao.DictEntityDao;
    import com.csf.study.params.RequestVO;
    import com.csf.study.service.EntityService;
    import org.apache.log4j.Logger;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import com.csf.study.domain.entity.DictEntity;
    import com.csf.study.dto.base.RespObj;
    
    import java.util.Date;
    import java.util.List;
    
    /**
     * @author fenglei.ma 2017/12/21 17:37
     */
    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    public class DictEntityControllerTest {
    
        private static final Logger logger = Logger.getLogger(DictEntityControllerTest.class);
    
        @Autowired
        private DictEntityController dictEntityController;
    
        @Autowired
        private EntityService entityService;
    
        @Autowired
        private DictEntityDao dictEntityDao;
    
        // 新增操作
        @Test
        public void tesdDaofindById() throws Exception {
            DictEntity entity = new DictEntity();
            entity.setName("成都样子");
            entity.setWord("趋势");
            entity.setType(3);
            entity.setUpt(new Date());
            entity.setCrt(new Date());
            entity.setUpu("SO893171");
            entity.setState(2);
            entity.setLastmodifiedBy("47542004755");
            
            RespObj result = dictEntityController.save(entity);
            logger.info("结果为 = " + result);
        }
    
         // 更新操作
        @Test
        public void updateId() throws Exception {
            DictEntity one = dictEntityDao.findOne(4l);
            one.setCru("74275121");
            one.setLastmodifiedBy("144111111111");
            one.setUpt(new Date());
            one.setUpu("SO7141");
            RespObj result = dictEntityController.save(one);
            logger.info("结果为 = " + result);
        }
    
        @Test
        public void tesd() throws Exception {
            RequestVO param = new RequestVO();
            param.setName("liu.fengxi");
            param.setWord("小仙");
    
            RespObj result = dictEntityController.findByNameAanWordZ(param);
            logger.info("结果为 = " + result);
        }
    
        @Test
        public void findAll() throws Exception {
            List<DictEntity> all = entityService.findAll();
            logger.info("结果为 = " + all);
        }
    
        @Test
        public void getEntityList() throws Exception {
            List<DictEntity> all = entityService.getEntityList();
            logger.info("结果为 = " + all);
    
            entityService.insertEntity();
        }
    
        @Test
        public void jdbcInsert() throws Exception {
            entityService.update();
        }
    
    
    }
  • 相关阅读:
    滚动条美化插件 nicescroll
    百度地图api
    Echarts的重点
    3月20号课堂随笔
    循环for语句
    有关一些CSS的基本内容
    HTML基本标签和一些注释的问题
    2018年3月17号的随堂笔记
    03.15补习
    for 的相关用法
  • 原文地址:https://www.cnblogs.com/xiaolei2017/p/8883087.html
Copyright © 2011-2022 走看看