SpringBoot、SpringData、Hibernate、MyBatis整合进行微、轻量级服务接口开发,然后结合freemarker和Jsp进行前后端结合。

1、开发准备

          开发工具:IntelliJ IDEA 2018.1;开发环境:jdk1.8_181 Version ; maven_3.5.3 Version (maven用远程仓库映射)

2、开始开发

      2.1 搭建开发环境

          点击 :File -->New -->Project

SpringBoot、SpringData、Hibernate、MyBatis整合进行微、轻量级服务接口开发,然后结合freemarker和Jsp进行前后端结合。_第1张图片

点击project后,开始选择要生成的project,这里选择spring Initializr

SpringBoot、SpringData、Hibernate、MyBatis整合进行微、轻量级服务接口开发,然后结合freemarker和Jsp进行前后端结合。_第2张图片

说明:我这里本机配置了JDK1.7和1.8版本的SDK,这里如果有小伙伴不知道SDK怎么配置可以查看我去年5月份的一篇博客地址为:https://blog.csdn.net/CDW2328/article/details/72627280

接着就点击NEXT.然后按照下图的搞:

SpringBoot、SpringData、Hibernate、MyBatis整合进行微、轻量级服务接口开发,然后结合freemarker和Jsp进行前后端结合。_第3张图片

点击Next,这里SpringBoot选择1.5.17,选择其他的版本会启动报错。

SpringBoot、SpringData、Hibernate、MyBatis整合进行微、轻量级服务接口开发,然后结合freemarker和Jsp进行前后端结合。_第4张图片

SpringBoot、SpringData、Hibernate、MyBatis整合进行微、轻量级服务接口开发,然后结合freemarker和Jsp进行前后端结合。_第5张图片

以下是了解的内容,不需要选择:

SpringBoot、SpringData、Hibernate、MyBatis整合进行微、轻量级服务接口开发,然后结合freemarker和Jsp进行前后端结合。_第6张图片

SpringBoot、SpringData、Hibernate、MyBatis整合进行微、轻量级服务接口开发,然后结合freemarker和Jsp进行前后端结合。_第7张图片

SpringBoot、SpringData、Hibernate、MyBatis整合进行微、轻量级服务接口开发,然后结合freemarker和Jsp进行前后端结合。_第8张图片

Next后点击Finish即可。

项目自动构建完毕以后,我们加一段代码,然后用浏览器访问,如果浏览器输出我们定义的WelCome to SpringBootData。那就搭建成功了。

SpringBoot、SpringData、Hibernate、MyBatis整合进行微、轻量级服务接口开发,然后结合freemarker和Jsp进行前后端结合。_第9张图片

写好以后,启动这个main方法,这里不需要指定Tomcat的路径,因为SpringBoot内嵌了Tomcat。

浏览器的地址栏输入:http://localhost:8080/getSpringBootData,如我们所愿正常输出了。

SpringBoot、SpringData、Hibernate、MyBatis整合进行微、轻量级服务接口开发,然后结合freemarker和Jsp进行前后端结合。_第10张图片

3、开始集成SpringData

      3.1、添加SpringData的maven依赖:


    org.springframework.boot
    spring-boot-starter-data-jpa

     3.2、既然SpringData是基于Jpa的持久化层框架,那么一定会个数据库交互,现在我们添加数据库配置文件。在项目的resources下创建一个properties文件(DataBaseConfig.properties)与application.properties文件同级。

     3.3、开始往数据库配置文件DataBaseConfig.properties中添加数据库链接配置:

db.driverClassName = com.mysql.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/betterlife_kaifa?useUnicode=true&characterEncoding=UTF-8
db.username = root
db.password = 123456
db.filters=stat  
db.initialSize=10  
db.maxWait=60000  
db.minIdle=100  
db.maxActive=200  
db.timeBetweenEvictionRunsMillis=60000  
db.minEvictableIdleTimeMillis=300000
db.validationQuery=SELECT 'x'  
db.testWhileIdle=true  
db.testOnBorrow=false  
db.testOnReturn=false  
db.poolPreparedStatements=true
db.maxOpenPreparedStatements=20 

至此数据库配置完毕,下面我们开始写基于无XML方式的IOC对象创建配置。

3.4创建一个包名字随便这里我取:Config

既然是SpringBoot的开发初衷是极大的简化基于Spring的XML方式,而且我们要指定数据源也就是数据库要用那个,所以我们采用创建java对象的方式来完成数据库链接初始化和其他的操作。

在我们新建的Config包里创建第一个java对象,这个java对象的左右是完成数据库链接检测和初始化数据库资源与创建事务管理等,不多说直接上代码。

package com.baidu.springbootdata.Config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

/**
 * @describe:数据库连接池的配置
 * @author: chendawei
 * @date: 2018年11月6日10:41:22
 * @note:
 */
@Configuration
@ConfigurationProperties(prefix = "db")
@PropertySource(value = {"DataBaseConfig.properties"})
public class DataBaseConfig {

    @Autowired
    private Environment env;

    @Value("${db.initialSize}")
    private int initialSize;

    @Value("${db.maxWait}")
    private long maxWait;

    @Value("${db.maxActive}")
    private int maxActive;

    @Value("${db.timeBetweenEvictionRunsMillis}")
    private long timeBetweenEvictionRunsMillis;

    @Value("${db.maxOpenPreparedStatements}")
    private int maxOpenPreparedStatements;

    @Bean(name = "dataSource",initMethod = "init",destroyMethod = "close")
    public DruidDataSource dataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(env.getProperty("db.driverClassName"));
        druidDataSource.setUrl(env.getProperty("db.url"));
        druidDataSource.setUsername(env.getProperty("db.username"));
        druidDataSource.setPassword(env.getProperty("db.password"));
        druidDataSource.setInitialSize(initialSize);
        druidDataSource.setMaxWait(maxWait);
        druidDataSource.setMaxActive(maxActive);
        druidDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        druidDataSource.setValidationQuery(env.getProperty("db.validationQuery"));
        druidDataSource.setTestWhileIdle(Boolean.getBoolean(env.getProperty("db.validationQuery")));
        druidDataSource.setTestOnBorrow(Boolean.getBoolean(env.getProperty("db.testOnBorrow")));
        druidDataSource.setTestOnReturn(Boolean.getBoolean(env.getProperty("db.testOnReturn")));
        druidDataSource.setPoolPreparedStatements(Boolean.getBoolean(env.getProperty("db.poolPreparedStatements")));
        druidDataSource.setMaxOpenPreparedStatements(maxOpenPreparedStatements);
        return druidDataSource;
    }
    /***************  读取自定义的yml文件的bean  *****************/
    /**
     * 加载yml配置文件,根目录为resources
     * @return
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource("freemarkerConfig.yml"));
        pspc.setProperties(yaml.getObject());
        return pspc;
    }

    /***************  需要整合MyBatis时才用,不整合不用  *****************/
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/MyBatisDaoMapper/*.xml"));
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
        return sqlSessionFactory;
    }
}

这样我们的数据库链接的配置就已完成,对于读取yml文件和myBatis的sqlSessionFactory的方法,这里需要说明一下,我这里由构建项目时自动生成的application.properties文件里面目前是空的没有写任何的东西进去,而我自定义了一个yml文件用于配置freemarker模板引擎,所以我这里需要将自定义的yml文件初始化,这里也不是说用到freemarker的时候非要这样做,如果我们想把上面数据库相关的配置不想再properties文件里存放,也不想在application.properties文件里存放,就想自定义yml文件进行读取这个操作也必须得做。

这个freemarker模板引擎的配置文件freemarkerConfig.yml位于resource下和application.properties文件同级,下面是具体配置。

spring:
  freemarker:
    request-context-attribute: req #req访问request
    suffix: .html #后缀名也可以修改为.ftl
    context-type: text/html
    enabled: true
    cache: false
    charset: UTF-8
    template-loader-path: classpath:/templates/ #模板路径,按需配置可加二级目录。默认为templates,
    settings:
      number_format: '0.##' #数字格式化,无小数点

myBatis的sqlSessionFactory是myBatis的会话管理,这里如果不需要整合这里就不要配置了,但是如果要整合必须和数据库的配置放置到一个对象中。

接下来,我们整合SpringData,整合springData的时候呢,我这里重新创建一个对象,用于专门来创建SpringData,在创建SpringData的时候我们顺便把Hibernate的会话代理也同样给搞完。上代码:

package com.baidu.springbootdata.Config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @describe:
 * @author: chendawei
 * @date: 2018年11月6日15:53:39
 * @note:
 */
@Configuration
@EnableJpaRepositories("com.baidu.springbootdata.SpringDataDao")
@EnableTransactionManagement
public class JpaConfig {

    @Resource
    DataSource dataSource;

    @Bean(name = "entityManagerFactory")
    public EntityManagerFactory entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        //此处com.example.*.model是你的java bean所在的包名
        factory.setPackagesToScan("com.baidu.springbootdata.PO");
        factory.setDataSource(dataSource);

        Map jpaProperties = new HashMap();
        jpaProperties.put("hibernate.ejb.naming_strategy","org.hibernate.cfg.ImprovedNamingStrategy");
        jpaProperties.put("hibernate.jdbc.batch_size",50);

        factory.setJpaPropertyMap(jpaProperties);
        factory.afterPropertiesSet();
        return factory.getObject();
    }

    @Bean(name="transactionManager")
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory());
        return txManager;
    }
}

至此就高完了SpringData和Hibernate的JPA持久化配置,看到这有同行看到说,我没有看到Hibernate的配置啊。在这里

Map jpaProperties = new HashMap(); jpaProperties.put("hibernate.ejb.naming_strategy","org.hibernate.cfg.ImprovedNamingStrategy"); jpaProperties.put("hibernate.jdbc.batch_size",50);

这一段就是将Hiberane的持久化配置完成了。有人会问这叫什么配置啊,好了不多说我们来看看这一段的意思和源码怎么配置的。这点我就不在这里详细描述,当写完这篇心得后我将详细探讨。其实这个还是用的spring的orm持久化方式。

至此我们已经将主要也是最重要的配置就高完了,接下来我们就加入测试类的代码:

我们来先展示一下项目下所有包和包下的文件。

src目录下的:

SpringBoot、SpringData、Hibernate、MyBatis整合进行微、轻量级服务接口开发,然后结合freemarker和Jsp进行前后端结合。_第11张图片

resource下的:

SpringBoot、SpringData、Hibernate、MyBatis整合进行微、轻量级服务接口开发,然后结合freemarker和Jsp进行前后端结合。_第12张图片

项目启动类的代码:

package com.baidu.springbootdata;

import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@EnableAutoConfiguration
@EnableTransactionManagement
public class SpringbootdataApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootdataApplication.class, args);
    }
}

controller层测试代码:

package com.baidu.springbootdata.Controller;

import com.baidu.springbootdata.EO.CardVoucherEO;
import com.baidu.springbootdata.Service.CardVoucherService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @describe:
 * @author: chendawei
 * @date: {DATE}{TIME}
 * @note:
 */
@Controller
@RequestMapping("/TestController")
public class TestController {

    public static final Logger logger = LoggerFactory.getLogger(TestController.class);

    @Autowired
    CardVoucherService cardVoucherService;

    /**
     * 获取用户的卡券的信息
     * @param userId
     * @return
     */
    @RequestMapping("/getUserCardVoucherMsg")
    public @ResponseBody List getUserCardVoucherMsg(@RequestBody String userId){
        JSONObject jsonObject = JSONObject.fromObject(userId.substring(1,userId.length()-1));
        Long userid = Long.parseLong(jsonObject.getString("userId"));
        System.out.println(userid);
        return this.cardVoucherService.getUserCardVoucherMsg(userid);
    }
}

hibernateDao的代码:

package com.baidu.springbootdata.HibernateDao;


import java.util.List;
import java.util.Map;

/**
 * @describe:
 * @author: chendawei
 * @date: {DATE}{TIME}
 * @note:
 */
public interface CardVoucherDao {

    List getUserCardVoucherMassage();
}
package com.baidu.springbootdata.HibernateDao.HibernateDaoImpl;


import com.baidu.springbootdata.HibernateDao.CardVoucherDao;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.Map;

/**
 * @describe:
 * @author: chendawei
 * @date: {DATE}{TIME}
 * @note:
 */
@Repository
public class CardVoucherDaoIpml implements CardVoucherDao {

    protected EntityManager entityManager = null;

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public List getUserCardVoucherMassage(){
        Session session = entityManager.unwrap(Session.class);
        SQLQuery sqlQuery = session.createSQLQuery("SELECT * FROM mhsh_card_voucher_info t WHERE id=137");
       return  sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
    }
}

myBatisDao的代码:

package com.baidu.springbootdata.MyBatisDao;

import com.baidu.springbootdata.PO.CardVoucherPO;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @describe:
 * @author: chendawei
 * @date: {DATE}{TIME}
 * @note:
 */
@Configuration
@Repository
@Mapper
public interface CardVouchersDao {

    Integer findCardVoucherMsg(Long userId);
}

SpringData的代码:

package com.baidu.springbootdata.SpringDataDao;

import com.baidu.springbootdata.PO.CardVoucherPO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;



/**
 * description:我的卡券的持久化层
 * @author chendawei
 * @authorTime 2018年7月17日上午10:29:13
 */
@Repository
public interface CardVoucherRepo extends JpaRepository {

    /**
     * 获取某一个用户卡券的所有信息
     * @param userId
     * @return
     */
    @Query("SELECT t FROM CardVoucherPO t WHERE t.userId=?1")
    List getUserCardVoucherMsg(Long userId);
}

PO的代码:

package com.baidu.springbootdata.PO;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * description:我的卡券记录 PO
 * @author chendawei
 * @authorTime 2018年7月16日下午7:56:29
 */

@Entity
@Table(name="mhsh_card_voucher_info")
public class CardVoucherPO implements Serializable{

    /**
     * @see Serializable
     */
    private static final long serialVersionUID = -5086715909814483831L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;//主键

    @Column(name="user_id")
    private Long userId;//用户userid

    @Column(name="voucher_name")
    private String voucherName;//卡券名称

    @Column(name="voucher_code")
    private String voucherCode;//卡券编码

    @Column(name="voucher_type")
    private String voucherType;//卡券类型

    @Column(name="voucher_pic")
    private String voucherPic;//卡券对应的图标地址

    @Column(name="voucher_use_flag")
    private String voucherUseFlag;//卡券是否使用的标志

    @Column(name="voucher_look_flag")
    private String voucherLookFlag;//卡券是否查看的标志

    @Column(name="fake_delete")
    private String fakeDelete;//卡券删除标志(伪删除)

    @Column(name="voucher_germ_time")
    private Date voucherGermTime;//卡券使用起始时间

    @Column(name="voucher_end_time")
    private Date voucherEndTime;//卡券结束日期

    @Column(name="create_by")
    private String createBy;//创建用户

    @Column(name="create_time")
    private Date createTime;//创建日期

    @Column(name="modify_by")
    private String modifyBy;//修改执行者

    @Column(name="update_time")
    private Date updateTime;//修改日期

    @Column(name="card_source_name")
    private String cardSourceName;//卡券根源名称(卡券名称上面的一排小字)

    @Column(name="watermark_pic")
    private String watermarkPic;//水印图片的地址

    @Column(name="auxiliary_money")
    private String auxiliaryMoney;//抵用、优惠、代金等附属券的价格

    @Column(name="reserved_one")
    private String reservedOne;//预留字段1

    @Column(name="reserved_two")
    private String reservedTwo;//预留字段2

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getVoucherName() {
        return voucherName;
    }

    public void setVoucherName(String voucherName) {
        this.voucherName = voucherName;
    }

    public String getVoucherCode() {
        return voucherCode;
    }

    public void setVoucherCode(String voucherCode) {
        this.voucherCode = voucherCode;
    }

    public String getVoucherType() {
        return voucherType;
    }

    public void setVoucherType(String voucherType) {
        this.voucherType = voucherType;
    }

    public String getVoucherPic() {
        return voucherPic;
    }

    public void setVoucherPic(String voucherPic) {
        this.voucherPic = voucherPic;
    }

    public String getVoucherUseFlag() {
        return voucherUseFlag;
    }

    public void setVoucherUseFlag(String voucherUseFlag) {
        this.voucherUseFlag = voucherUseFlag;
    }

    public String getVoucherLookFlag() {
        return voucherLookFlag;
    }

    public void setVoucherLookFlag(String voucherLookFlag) {
        this.voucherLookFlag = voucherLookFlag;
    }

    public String getFakeDelete() {
        return fakeDelete;
    }

    public void setFakeDelete(String fakeDelete) {
        this.fakeDelete = fakeDelete;
    }

    public Date getVoucherGermTime() {
        return voucherGermTime;
    }

    public void setVoucherGermTime(Date voucherGermTime) {
        this.voucherGermTime = voucherGermTime;
    }

    public Date getVoucherEndTime() {
        return voucherEndTime;
    }

    public void setVoucherEndTime(Date voucherEndTime) {
        this.voucherEndTime = voucherEndTime;
    }

    public String getCreateBy() {
        return createBy;
    }

    public void setCreateBy(String createBy) {
        this.createBy = createBy;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public String getModifyBy() {
        return modifyBy;
    }

    public void setModifyBy(String modifyBy) {
        this.modifyBy = modifyBy;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public String getCardSourceName() {
        return cardSourceName;
    }

    public void setCardSourceName(String cardSourceName) {
        this.cardSourceName = cardSourceName;
    }

    public String getWatermarkPic() {
        return watermarkPic;
    }

    public void setWatermarkPic(String watermarkPic) {
        this.watermarkPic = watermarkPic;
    }

    public String getAuxiliaryMoney() {
        return auxiliaryMoney;
    }

    public void setAuxiliaryMoney(String auxiliaryMoney) {
        this.auxiliaryMoney = auxiliaryMoney;
    }

    public String getReservedOne() {
        return reservedOne;
    }

    public void setReservedOne(String reservedOne) {
        this.reservedOne = reservedOne;
    }

    public String getReservedTwo() {
        return reservedTwo;
    }

    public void setReservedTwo(String reservedTwo) {
        this.reservedTwo = reservedTwo;
    }

    @Override
    public String toString() {
        return "CardVoucherPO [id=" + id + ", userId=" + userId + ", voucherName=" + voucherName + ", voucherCode="
                + voucherCode + ", voucherType=" + voucherType + ", voucherPic=" + voucherPic + ", voucherUseFlag="
                + voucherUseFlag + ", voucherLookFlag=" + voucherLookFlag + ", fakeDelete=" + fakeDelete
                + ", voucherGermTime=" + voucherGermTime + ", voucherEndTime=" + voucherEndTime + ", createBy="
                + createBy + ", createTime=" + createTime + ", modifyBy=" + modifyBy + ", updateTime=" + updateTime
                + ", cardSourceName=" + cardSourceName + ", watermarkPic=" + watermarkPic + ", auxiliaryMoney="
                + auxiliaryMoney + ", reservedOne=" + reservedOne + ", reservedTwo=" + reservedTwo + "]";
    }
}

myBatisDao包里接口对象和接口方法对应的MapperXML:




    

service接口代码:

package com.baidu.springbootdata.Service;

import com.baidu.springbootdata.EO.CardVoucherEO;

import java.util.List;

/**
 * author:chendawei
 * time:2018年10月31日15:58:32
 */
public interface CardVoucherService {

    List getUserCardVoucherMsg(Long userId);

}

serviceImpl实现类的代码:

package com.baidu.springbootdata.Service.ServiceImpl;

import com.baidu.springbootdata.EO.CardVoucherEO;
import com.baidu.springbootdata.HibernateDao.CardVoucherDao;
import com.baidu.springbootdata.MyBatisDao.CardVouchersDao;
import com.baidu.springbootdata.PO.CardVoucherPO;
import com.baidu.springbootdata.Service.CardVoucherService;
import com.baidu.springbootdata.SpringDataDao.CardVoucherRepo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service(value = "CardVoucherService")
public class CardVoucherServiceImpl implements CardVoucherService {

    @Autowired
    private CardVoucherRepo cardVoucherRepo;

    @Autowired
    private CardVoucherDao cardVoucherDao;

    @Autowired
    private CardVouchersDao cardVouchersDao;

    @SuppressWarnings("all")
    @Override
    public List getUserCardVoucherMsg(Long userId) {
        List cardVoucherEoList = new ArrayList();
        List listMap =  this.cardVoucherDao.getUserCardVoucherMassage();
        System.out.println(listMap);
        Integer listMap1 =  this.cardVouchersDao.findCardVoucherMsg(userId);
        System.out.println(listMap1);
        if (userId != null && userId > 0) {
            List cardVoucherPoList = this.cardVoucherRepo.getUserCardVoucherMsg(userId);
            if (cardVoucherPoList.size() > 0) {
                for (CardVoucherPO cardVoucherPO : cardVoucherPoList) {
                    CardVoucherEO cardVoucherEO = new CardVoucherEO();
                    BeanUtils.copyProperties(cardVoucherPO, cardVoucherEO);
                    cardVoucherEoList.add(cardVoucherEO);
                }
                return cardVoucherEoList;
            } else {
                cardVoucherEoList.add(null);
                return cardVoucherEoList;
            }
        } else {
            cardVoucherEoList.add(null);
            return cardVoucherEoList;
        }
    }


}

测试freemarker的html代码:




    
    TestFreeMarker
   
    


    


pom.xml文件:



    4.0.0

    com.baidu
    springbootdata
    0.0.1-SNAPSHOT
    jar

    springbootdata
    Spring_BootDataDemo

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.17.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-configuration-processor
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.boot
            spring-boot-starter-aop
        
        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.1
        
        
        
            org.springframework.boot
            spring-boot-starter-freemarker
        
        
        
            org.yaml
            snakeyaml
            ${snakeyaml.version}
        
        
        
            mysql
            mysql-connector-java
            5.1.34
        
        
        
            com.alibaba
            druid
            1.0.27
        
        
        
            log4j
            log4j
            1.2.12
        
        
        
            jstl
            jstl
            1.2
        
        
            javax.servlet
            javax.servlet-api
            3.0.1
            provided
        
        
            net.sf.json-lib
            json-lib
            2.4
        
        
            junit
            junit
            4.8.2
            test
        
        
            javax.persistence
            persistence-api
            1.0
        
        
            org.aspectj
            aspectjrt
            1.8.0
        
        
            org.aspectj
            aspectjweaver
            1.8.0
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
        
            
                src/main/java
                
                    *.xml
                
                false
            
        
    

好至此呢,SpringBoot整合SpringData、Mybatis、Hibernate就已经结束了,Freemarker我只是进行了简单配置,当然Feemarker的标签还有很多比如,取值,循环,判断等等。这里都可以用在项目中。

最后我把整合Jsp的步骤记录一下:

首先我们要知道SpringBoot对jsp的支持不太好,我们需要手动的把jsp相关的加进来。

第一在pom.xml中添加依赖(项目中不需要整合jsp则不需要添加这些依赖):


        
            org.apache.tomcat.embed
            tomcat-embed-jasper
        

        
            javax.servlet
            jstl
            compile
        

第二手动创建webapp目录以及子目录WEB-INF、jsp和测试的Jsp页面,注意webapp创建到和resource目录的同级并列。

webapp的子目录是WEB-INF,WEB-INF的子目录是jsp目录,jsp目录里面存放jsp页面文件。

第三创建jsp文件的配置JspConfig.yml文件,这里的配置是yml文件。文件位置位于resource目录下和上面的freemarkerConfig.yml文件同级。

JspConfig.yml文件:

spring:
    mvc:
      view:
        prefix: /WEB-INF/jsp/
        suffix: .jsp

第四,编写初始化配置文件的方法,在DataBaseConfig.java文件中添加这个方法:

@Bean
 public static PropertySourcesPlaceholderConfigurer propertie() {
     PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
     YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
     yaml.setResources(new ClassPathResource("JspConfig.yml"));
     pspc.setProperties(yaml.getObject());
     return pspc;
 }

注意:我在添加jsp页面的初始化配置之前,已经添加过初始化freemarker模板引擎的方法,这两个方法不能共存,要不然谁也访问不到各自的页面,说白了就是不能同时配置两种视图。当然要是嫌写两个方法麻烦每次还得注释那就直接把上面代码中的yaml.setResources(new ClassPathResource("JspConfig.yml"));里的JspConfig.yml改为FreemarkerConfig.yml。就行互相切换使用呗。

至此我整合完毕。如有错误处请大神指教。。。。QQ号:767611329,鲍家街58号

你可能感兴趣的:(JavaEE框架,分布式,微服务架构)