精华内容
下载资源
问答
  • Spring Boot入门 Spring Boot整合MyBatis Spring Boot集成JSP 一、初始化项目 1、地址:https://start.spring.io/ 2、相关配置选项如下,然后创建项目 3、导入Eclipse (步骤:Import --- Import --- ...

        Spring Boot入门 Spring Boot整合MyBatis Spring Boot集成JSP

     

    一、初始化项目

    1、地址:https://start.spring.io/

    2、相关配置选项如下,然后创建项目

    3、导入Eclipse (步骤:Import --- Import --- Maven --- Existing Maven Projects )

     

     

    二、Spring Boot Hello World!

    1、引入web支持

    <!-- 引入 web 支持 -->
    	<dependency>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-web</artifactId>
    		<scope>compile</scope>
    	</dependency>

     

    2、创建 HelloWorldController

    @RestController
    public class HelloWorldController {
    	@RequestMapping(value = {})
    	public String hello(String productName) {
    		return "hello world! --->" +productName;
    	}
    }

     

    3、启动项目: SpringboottouristApplication --- Run As --- Java Application

    4、浏览器输入: http://localhost:8080/springboottourist

    5、结果如下:

    三、整合 MyBatis

    1、添加MyBatis 依赖 ,MySQL驱动 

    <!-- 引入 spring boot MyBatis 依赖 -->
    	<dependency>
    		<groupId>org.mybatis.spring.boot</groupId>
    		<artifactId>mybatis-spring-boot-starter</artifactId>
    		<version>2.0.0</version>
    	</dependency>
    		
    	<!-- 引入 MySQL connector 驱动 -->
    	<dependency>
    		<groupId>mysql</groupId>
    		<artifactId>mysql-connector-java</artifactId>
    	</dependency>

     

    2、在 application.properties 配置文件中添加 MySQL、MyBatis相关配置信息

    ## 数据源配置
    spring.datasource.url=jdbc:mysql://localhost/chapter?useSSL=false&useUnicode=true&characterEncoding=utf-8
    spring.datasource.username=root
    spring.datasource.password=root
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    
    ## Mybatis 配置
    # 配置 实体类包路径。 typeAliasesPackage
    mybatis.typeAliasesPackage=com.runcode.mybatis.entity
    # 配置扫描 MyBatis XML 文件路径 mapperLocations
    mybatis.mapperLocations=classpath:mapping/**/*.xml
    
    # 配置 server path 路径
    server.servlet.context-path = /mybatis

     

    3、 创建 User表

    SET FOREIGN_KEY_CHECKS=0;
    -- ----------------------------
    -- Table structure for user
    -- ----------------------------
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(255) DEFAULT NULL,
      `age` varchar(255) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=48 DEFAULT CHARSET=utf8;

     

    4.1、User 实体类

    public class User {
    
        /** 编号 */
        private Integer id;
    
        /** 姓名 */
        private String name;
    
        /** 年龄 */
        private int age;
    
        // ====== 省略 getter , setter ====== //
    }
    
    

     

    4.2、UserDao

    public interface UserDao {
    	int insert(User user);
    	int delete(User user);
    	int update(User user);
    	User get(User user);
    	User get(int id);
    	List<User> getList(User user);
    }

     

    4.3、UserService

          同 4.2 UserDao 略!

     

    4.4 UserController

    @RestController
    @RequestMapping(value = "/user")
    public class UserController {
    	private Logger logger = LoggerFactory.getLogger(UserController.class);
    	
    	@Autowired
    	private UserService userService ;
    	
    	@RequestMapping(value = "/insert")
    	public Boolean insert(User user) {
    		logger.debug(" 插入数据: insert {} insert");
    		return userService.insert(user) ;
    	}
    	
    	@RequestMapping(value = "/delete")
    	public Boolean delete(User user) {
    		logger.debug(" 删除数据: delete {} delete");
    		return userService.delete(user) ;
    	}
    	
    	@RequestMapping(value = "/update")
    	public Boolean update(User user) {
    		logger.debug(" 修改数据: update {} update");
    		return userService.update(user) ;
    	}
    	
    	@RequestMapping(value = "/get")
    	public User get(User user) {
    		logger.debug(" 获取一条数据: get {} get ");
    		return userService.get(user) ;
    	}
    	
    	@RequestMapping(value = {"/getList","" , "list"})
    	public List<User> getList(User user) {
    		logger.debug(" 获取list数据: getList {} getList");
    		return userService.getList(user) ;
    	}
    }

     

    5、MyBatisApplication 启动程序入口类

    @SpringBootApplication
    @MapperScan(value = {"com.runcode.mybatis.dao"})
    public class MyBatisApplication {
    	public static void main(String[] args) {
    		SpringApplication.run(MyBatisApplication.class, args);
    		System.out.println("main application running ... ");
    	}
    }

     

    6、目录结构如下:

     

    7、启动程序: MyBatisApplication --- 右键 --- Run As --- Java Application

     

    8、测试: http://localhost:8080/mybatis/user , 可以看到用户表全部 JSON数据输出

     

     

    四、整合 JSP

    1、添加 Tomcat 支持, jstl 标签库

    <!-- tomcat支持 -->
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-tomcat</artifactId>
               <scope>provided</scope>
           </dependency>
           <dependency>
               <groupId>org.apache.tomcat.embed</groupId>
               <artifactId>tomcat-embed-jasper</artifactId>
               <scope>provided</scope>
           </dependency>
            <!-- jsp标签库 -->
            <dependency>
               <groupId>javax.servlet</groupId>
               <artifactId>jstl</artifactId>
           </dependency>
    

     

    2、application.properties 添加 JSP 相关配置

    # SpringMVC 相关配置
    spring.mvc.view.prefix=/WEB-INF/views/
    spring.mvc.view.suffix=.jsp

     

    3、创建一个 JspController

    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    @RequestMapping(value="/jsp")
    @Controller
    public class JspController {
    	@RequestMapping(value = "/index")
    	public String index(Model model) {
    		model.addAttribute("name", "Spring Boot 返回JSP页面@!");
    		return "index";
    	}
    }

     

    4、在 src/main下创建目录: /webapp/WEB-INF/views/index.jsp 如下:

      (补充:jsp文件不能放在 resouces目录下,jsp文件不会编译。请自行补充知识点: maven 约定, jsp执行原理!

    5、index.jsp 文件详情

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    	<h1> spring boot - jsp </h1>
    	<h3>${name }</h3>
    </body>
    </html>

     

    6、启动程序: JspApplication --- 右键 --- Run As --- Java Application

    7、测试:http://localhost:8080/mybatis/jsp/index 如下

    五、总结

    1、初始化Spring Boot 项目,Eclipse 、 Idea 都有对应的插件,无需到 https://start.spring.io/ 去下载项目。

    2、整合MyBatis:配置数据源,实体类映射路径,扫描包xml文件路径即可。 也可以直接使用MyBatis 注解开发,不用写xml文件。

    3、整合JSP:需要添加Tomcat支持,JSTL标准标签库。(其实,官方不推荐使用JSP,毕竟效率低,占内存。)

    4、Spring Boot + MyBatis + JSP 整合起来,成为了曾经流行的 SSM 项目。

    5、本示例提供代码下载: https://gitee.com/RunCoder/spring-boot-tourist/tree/feature-mybatis-jsp/ (请注意切换分支,不会下载,可私信联系,谢谢。)

    6、遗留问题: Spring Boot 整合JSP,打包后无法JSP页面了。

     

     

    展开全文
  • 最近正在准备面试,由于之前学习了spring boot,突然想在spring boot项目中集成spring security来做认证和授权,接下来就以一个详细的项目进行描述(这里使用IDEA来进行): 一、项目创建 1、新建项目。 2、填...

    最近正在准备面试,由于之前学习了spring boot,突然想在spring boot项目中集成spring security来做认证和授权,接下来就以一个详细的项目进行描述(这里使用IDEA来进行):

    一、项目创建

    1、新建项目。

    2、填入项目信息。

    3、选择所需的框架,这里使用到了Spring Boot、Spring Security和Mybatis,数据库使用MySQL。

     

    4、现在项目存放的地址,单击finish即可 。

    至此项目已经创建成功了!

     6、准备数据库和数据表。数据库名称plans

    /*
     Navicat Premium Data Transfer
    
     Source Server         : mysql
     Source Server Type    : MySQL
     Source Server Version : 50719
     Source Host           : localhost:3306
     Source Schema         : plans
    
     Target Server Type    : MySQL
     Target Server Version : 50719
     File Encoding         : 65001
    
     Date: 07/03/2019 17:34:43
    */
    
    SET NAMES utf8mb4;
    SET FOREIGN_KEY_CHECKS = 0;
    
    -- ----------------------------
    -- Table structure for plan
    -- ----------------------------
    DROP TABLE IF EXISTS `plan`;
    CREATE TABLE `plan`  (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(45) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      `content` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      `createtime` datetime(0) NULL DEFAULT NULL,
      `finishtime` datetime(0) NULL DEFAULT NULL,
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Table structure for user
    -- ----------------------------
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user`  (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      `password` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      `username` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
    
    SET FOREIGN_KEY_CHECKS = 1;
    

    二、接下来看一下项目:

    1、项目的pom文件中已经添加相应的依赖如下所示:

     <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-security</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.0.0</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
            </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.security</groupId>
                <artifactId>spring-security-test</artifactId>
                <scope>test</scope>
            </dependency>

    2、这时我们需要自定义实现UserDetailsService接口,定义如下。

    package cn.xiaoyue.myplan.service;
    
    import cn.xiaoyue.myplan.dao.UserDao;
    import cn.xiaoyue.myplan.model.User;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.authority.SimpleGrantedAuthority;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.core.userdetails.UsernameNotFoundException;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class CussomUserService implements UserDetailsService {
        @Autowired
        private UserDao userDao;
    
        @Override
        public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
            User user= userDao.findUserByUserName(s);//User类是自定义的类
            List<GrantedAuthority> authorities=new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            return new org.springframework.security.core.userdetails.User(user.getUserName(),user.getPassword(),authorities);
        }
    }
    

    userDao.findUserByUserName(s)是使用Mybatis来读取数据库中数据。

    除此之外,我们还需在spring security的配置文件中注册CustomUserService,代码如下。

    package cn.xiaoyue.myplan.config;
    
    import cn.xiaoyue.myplan.service.CussomUserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.builders.WebSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.core.userdetails.UserDetailsService;
    
    import javax.swing.text.Caret;
    
    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            super.configure(http);
        }
    
        @Bean
        protected UserDetailsService userDetailsService() {
            return new CussomUserService();
        }
    
        @Override
        public void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService()).passwordEncoder(new CustomPasswordEncoder());//passwordEncoder是为了解决There is no PasswordEncoder mapped for the id "null"
        }
    
        @Override
        public void configure(WebSecurity web) throws Exception {
            super.configure(web);
        }
    }

    至此Spring Security的认证基本完成了,这里面认证的数据来源于数据库plans的user表中。

    项目演示如下:

    认证成功跳转到首页 

    展开全文
  • 此处默认已配置好连接池,如果不清楚连接池配置的,请参考:spring boot:spring boot2.0配置druid连接池 &amp;amp;lt;!-- mybatis --&amp;amp;gt; &amp;amp;lt;dependency&amp;amp;gt;

    如何集成

    添加依赖

    此处默认已配置好连接池,如果不清楚连接池配置的,请参考:spring boot:spring boot2.0配置druid连接池

            <!-- mybatis -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.2</version>
            </dependency>
    
            <!-- mybatis分页插件 -->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper-spring-boot-starter</artifactId>
                <version>1.2.10</version>
            </dependency>
    

    建议有分页情况下,使用分页插件,既可以使代码变得简洁,利于维护,也可以提高开发效率。

    代码生成器

    一般情况下,使用mybatis都不会自己去写modeldao,和mapper,这里推荐我常用的代码生成器:

    1. mybatis-generator-core

    所有的mybatis代码生成器都是基于原生mybatis-generator开始修改的,我这里加了中文注释功能,有兴趣的同学可以继续自己修改。

    1. mybatis-generator-gui

    带界面的代码生成器,功能还比较齐全,对mybatis-generator-core使用方法还不太了解的同学可以选择这个。

    编辑配置文件

    #mybatis xml文件位置
    mybatis.mapper-locations=classpath:mapper/*.xml
    #打印SQL
    logging.level.com.ouyanglol.demo.dao=debug
    

    添加MapperScan

    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    /**
     * @author Ouyang
     */
    @SpringBootApplication
    @MapperScan(basePackages = "com.ouyanglol.demo.dao")
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    }
    

    如果不配置@MapperScanmybaties的没一个Mapper类都需要添加@Mapper注解,很麻烦,建议使用@MapperScan

    测试

    测试代码

    controller

    package com.ouyanglol.demo.controller;
    
    import com.github.pagehelper.PageInfo;
    import com.ouyanglol.demo.model.User;
    import com.ouyanglol.demo.service.UserService;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @author Ouyang
     */
    @RestController
    @RequestMapping("user")
    @Slf4j
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        @GetMapping("list")
        public String list() {
            PageInfo<User> pageInfo = userService.all();
            log.info("total-->{}",pageInfo.getTotal());
            StringBuilder builder = new StringBuilder();
            pageInfo.getList().forEach(user -> builder.append(user.toString()));
            log.info("userList-->{}",builder.toString());
            log.info("一共{}页",pageInfo.getPages());
            return builder.toString();
        }
    }
    

    service

    import com.github.pagehelper.PageInfo;
    import com.ouyanglol.demo.model.User;
    
    /**
     * @author Ouyang
     */
    public interface UserService {
    
        /**
         * 查询所有用户
         * @return 用户列表
         */
        PageInfo<User> all();
    
    }
    
    import com.github.pagehelper.PageHelper;
    import com.github.pagehelper.PageInfo;
    import com.ouyanglol.demo.dao.UserDAO;
    import com.ouyanglol.demo.model.User;
    import com.ouyanglol.demo.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    
    /**
     * @author Ouyang
     */
    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserDAO userDAO;
    
        @Override
        public PageInfo<User> all() {
            //开始分页,查询第1页,每页3条数据
            PageHelper.startPage(1,3);
            return new PageInfo<>(userDAO.selectAll());
        }
    }
    
    

    dao

    package com.ouyanglol.demo.dao;
    
    import java.io.Serializable;
    
    /**
     * DAO公共基类,由MybatisGenerator自动生成请勿修改
     * @author Ouyang
     * @param <Model> The Model Class 这里是泛型不是Model类
     * @param <PK> The Primary Key Class 如果是无主键,则可以用Model来跳过,如果是多主键则是Key类
     */
    public interface MyBatisBaseDao<Model, PK extends Serializable> {
        /**
         * 删除
         * @param id 主键
         * @return int
         */
        int deleteByPrimaryKey(PK id);
    
        /**
         * 添加
         * @param record 实体
         * @return int
         */
        int insert(Model record);
    
        /**
         * 增加
         * @param record 实体
         * @return int
         */
        int insertSelective(Model record);
    
        /**
         * 根据主键查询
         * @param id id
         * @return 实体
         */
        Model selectByPrimaryKey(PK id);
    
        /**
         * 更新
         * @param record 实体
         * @return int
         */
        int updateByPrimaryKeySelective(Model record);
    
        /**
         * 更新
         * @param record 实体
         * @return int
         */
        int updateByPrimaryKey(Model record);
    }
    
    package com.ouyanglol.demo.dao;
    
    import com.ouyanglol.demo.model.User;
    
    import java.util.List;
    
    /**
     * UserDAO继承基类
     * @author Ouyang
     */
    public interface UserDAO extends MyBatisBaseDao<User, String> {
        /**
         * 查询所有用户
         * @return 用户列表
         */
        List<User> selectAll();
    }
    

    mapper

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.ouyanglol.demo.dao.UserDAO">
        <resultMap id="BaseResultMap" type="com.ouyanglol.demo.model.User">
            <id column="id" jdbcType="VARCHAR" property="id"/>
            <result column="userName" jdbcType="VARCHAR" property="username"/>
            <result column="sex" jdbcType="VARCHAR" property="sex"/>
            <result column="age" jdbcType="INTEGER" property="age"/>
        </resultMap>
        <sql id="Base_Column_List">
          id, userName, sex, age
        </sql>
        <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
            select
            <include refid="Base_Column_List"/>
            from user
            where id = #{id,jdbcType=VARCHAR}
        </select>
        <select id="selectAll" resultType="com.ouyanglol.demo.model.User">
            select
            <include refid="Base_Column_List"/>
            from user
        </select>
        <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
        delete from user
        where id = #{id,jdbcType=VARCHAR}
      </delete>
        <insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.ouyanglol.demo.model.User"
                useGeneratedKeys="true">
        insert into user (userName, sex, age
          )
        values (#{username,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
          )
      </insert>
        <insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.ouyanglol.demo.model.User"
                useGeneratedKeys="true">
            insert into user
            <trim prefix="(" suffix=")" suffixOverrides=",">
                <if test="username != null">
                    userName,
                </if>
                <if test="sex != null">
                    sex,
                </if>
                <if test="age != null">
                    age,
                </if>
            </trim>
            <trim prefix="values (" suffix=")" suffixOverrides=",">
                <if test="username != null">
                    #{username,jdbcType=VARCHAR},
                </if>
                <if test="sex != null">
                    #{sex,jdbcType=VARCHAR},
                </if>
                <if test="age != null">
                    #{age,jdbcType=INTEGER},
                </if>
            </trim>
        </insert>
        <update id="updateByPrimaryKeySelective" parameterType="com.ouyanglol.demo.model.User">
            update user
            <set>
                <if test="username != null">
                    userName = #{username,jdbcType=VARCHAR},
                </if>
                <if test="sex != null">
                    sex = #{sex,jdbcType=VARCHAR},
                </if>
                <if test="age != null">
                    age = #{age,jdbcType=INTEGER},
                </if>
            </set>
            where id = #{id,jdbcType=VARCHAR}
        </update>
        <update id="updateByPrimaryKey" parameterType="com.ouyanglol.demo.model.User">
        update user
        set userName = #{username,jdbcType=VARCHAR},
          sex = #{sex,jdbcType=VARCHAR},
          age = #{age,jdbcType=INTEGER}
        where id = #{id,jdbcType=VARCHAR}
      </update>
    </mapper>
    

    测试类

    package com.ouyanglol.demo.controller;
    
    import com.ouyanglol.demo.DemoApplicationTests;
    import org.junit.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    
    import static org.junit.Assert.*;
    
    /**
     * @author Ouyang
     * @date 18/12/8 21:23
     */
    public class UserControllerTest  extends DemoApplicationTests {
    
        @Autowired
        private UserController userController;
    
        @Test
        public void list() {
            assertNotNull(userController.list());
        }
    }
    

    测试结果

    在这里插入图片描述

    图(1)

    查询没问题,分页插件也成功分页。

    项目地址

    地址:https://github.com/a252937166/spring-boot-demo
    分支:feature/mybatis

    参考文章

    https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md

    展开全文
  • Spring Boot集成Spring Data

    千次阅读 2016-01-28 10:43:17
    org.springframework.boot spring-boot-starter-parent 1.3.1.RELEASE mysql mysql-connector-java org.springframework.boot spring-boot-starter-jdbc

    1.pom.xml配置

    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>1.3.1.RELEASE</version>
    	</parent>
    
    	<dependencies>
    		<!-- MYSQL -->
    		<dependency>
    			<groupId>mysql</groupId>
    			<artifactId>mysql-connector-java</artifactId>
    		</dependency>
    		<!-- Spring Boot JDBC -->
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-jdbc</artifactId>
    		</dependency>
    
    		<!-- JDBC连接池组件 -->
    		<dependency>
    			<groupId>com.zaxxer</groupId>
    			<artifactId>HikariCP</artifactId>
    
    		</dependency>
    		<!-- Spring Boot Data JPA -->
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-data-jpa</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.data</groupId>
    			<artifactId>spring-data-commons</artifactId>
    		</dependency>
    		<!-- AOP -->
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-aop</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    		<!-- 应用容器 -->
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-jetty</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-tomcat</artifactId>
    		</dependency>
    		<!-- 日志管理log -->
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-log4j</artifactId>
    		</dependency>
    		<!-- Servlet -->
    		<dependency>
    			<groupId>javax.servlet</groupId>
    			<artifactId>javax.servlet-api</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-core</artifactId>
    		</dependency>
    	</dependencies>
    2.application.properties 配置数据源

    #JDBC
    spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
    spring.datasource.username=root
    spring.datasource.password=wbw123456
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    #spring.datasource.max-idle=10
    #spring.datasource.max-wait=10000
    #spring.datasource.min-idle=5
    #spring.datasource.initial-size=5
    #spring.datasource.validation-query=SELECT 1
    #spring.datasource.test-on-borrow=false
    #spring.datasource.test-while-idle=true
    #spring.datasource.time-between-eviction-runs-millis=18800
    #spring.datasource.jdbc-interceptors=ConnectionState;SlowQueryReport(threshold=0)
    #spring.datasource.type=com.zaxxer.hikari.HikariDataSource
    #JPA
    #spring.jpa.database=jdbc:mysql://localhost:3306/mydatabase
    #spring.jpa.show-sql=true
    #spring.jpa.properties.xxxxxxx=
    #spring.jpa.generate-ddl=
    #spring.jpa.open-in-view=
    #spring.jpa.database-platform=
    #spring.jpa.hibernate.ddl-auto=
    #spring.data.jpa.repositories.enabled=
    #spring.jpa.hibernate.naming-strategy.xxxxxxx=
    server.context-path=/xw
    server.port=8080
    
    
    
    3.定义Repository接口

    /**
     * 用户DAO 不需要添加@Repository注解
     * Spring会自动为我们继承CrudRepository接口的接口创建实现类 org.springframework.data.jpa.repository.support.SimpleJpaRepository
     * @author WANBGBOWE
     *
     */
    public interface UserRepository extends CrudRepository<User, Integer> {
    
    	//使用命名规范查询:fin 、findBy、read等
    	public User findByName(String name);
    	public List<User> findByNameAndAge(String name,String age);

    4.编写程序启动类

    
    /**
     * 
     * 启动器
     *
     */
    @SpringBootApplication
    public class Application1  implements CommandLineRunner{
    	
    	@Autowired
        private <span style="font-family: Arial, Helvetica, sans-serif;">UserRepository   </span>userRepository;
    	@Override
    	public void run(String... args) throws Exception {
    		<pre name="code" class="java">            User user = userRepository.<span style="font-family: Arial, Helvetica, sans-serif;">findByName('xx');</span>
    System.out.println(user);}public static void main(String[] args) { SpringApplication.run(Application1.class,args);}}

     
    


    展开全文
  • spring-boot集成spring-security

    千次阅读 2019-03-06 11:03:19
    这篇文章介绍下security在spring-boot中如何进行集成配置。 之前在学习Spring-security的时候还是使用传统的xml进行配置。基本上需要单独建一个xml文件来配置security,内容很多,也有小伙伴给我反馈说太复杂了。一...
  • spring boot集成 spring + spring MVC + mybatis + swagger + maven 第一步:选择Spring Initializr搭建spring boot 第二步:配置项目信息 第三步:选择项目需要的jar包 web必选的 我用的Mysql数据库...
  • Spring boot 集成Spring Data JPA+数据源 看了很多篇springboot 集成jpa的博客,但都是千篇一律,按部就班的编码后运行各种错误,根据自己的研究以下是自己编码的一个demo 配置文件 spring.datasource.driver...
  • Spring boot集成Mybatis

    2016-12-12 17:42:10
    上一篇文章:SpringMVC集成公用Mybatis Dao,写了Spring怎么集成Mybatis Dao,由于Spring boot的快速发展,现在记录下Spring boot如何集成mybatis。 一、首先项目引入Spring boot org.springframework.boot ...
  • 之前没有做过权限方面的,组长让我做下一版本的权限管理,去看了几篇博客,感觉写的不够清晰,自己...-- springboot spring security支持包 --&gt; &lt;dependency&gt; &lt;groupId&gt;org....
  • 1.环境 jdk1.8、elasticsearch-5.5.2:官网 1.1:pom <parent>...org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <vers...
  • Spring Boot面试题(2020最新版)

    万次阅读 多人点赞 2020-02-19 17:48:42
    文章目录概述什么是 Spring BootSpring Boot 有哪些优点?Spring Boot 的核心注解是哪个?它主要由哪几个注解组成的?配置什么是 JavaConfig?Spring Boot 自动配置原理是什么?你如何理解 Spring Boot 配置加载...
  • Spring Boot集成Mybatis

    千次阅读 2017-06-07 14:44:29
    1. 配置pom.xml 引入mybatis-spring-boot-starter。 org.springframework.boot spring-boot-starter-parent 1.3.5.RELEASE UTF-8 UTF-8 1.8 org.springframework.b
  • 1.创建项目启动报错 Field adminDao in com.cj.service.AdminService required a bean of type ‘com.cj.mapper.AdminDao’ that could not be...错误原因是启动类扫不到dao层的注解,所以在启动类上扫描的路径就可以了
  • 一、Spring Boot JPA 数据库: MySQL:支持注解实现id自增长 Oracle:需要配置序列 pom依赖:jpa、ojdbc(或mysql驱动) application.properties # 无表时,创建 spring.jpa.properties.hibernate.hbm2ddl....
  • Spring Boot整合SpringJPA

    2018-01-06 17:34:32
    Spring Boot整合SpringJPA pom文件引入依赖 parent> groupId>org.springframework.bootgroupId> artifactId>spring-boot-starter-parentartifactId> version>1.4.2.RELEASEversion> paren
  • spring security 最简单的demo 1.我们首先自定义资源接口访问权限 我们可以继承WebSecurityConfigurerAdapter类来进行控制,如下,我们定义/和/static/的资源不需要认证,其他除了登陆和登出都是需要验证的。并且...
  • 最近在学习spring cloud,首先简单的创建eureka-server,eureka-client,ribbon,feign…等等demo,然后开始集成mybatis,开始项目构建,下面开始分享一下我遇到的坑。 ...
  • 需要添加的依赖如下: <dependencies> <dependency>...org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
  • spring boot集成mybatis

    2020-11-23 11:28:29
    spring boot集成mybatis mybatis的有点就不说了,下面记录下如何在spring boot项目中添加mybatis依赖 创建一个spring boot项目 使用idea或其他工具快速创建一个spring web项目,可选择如下maven依赖: pom.xml文件...
  • 小插曲---(如果你们公司想使用spring cloud进行微服务改造,本人提供完整的解决方案 GITHUB 地址... 1 spring boot 集成 mybaits 2 mybatis使用XML作为数据源接...
  • Spring boot集成hibernate

    2020-04-13 15:40:41
    hibernate与spring boot集成 1,导入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 14,385
精华内容 5,754
关键字:

bootdaospring集成

spring 订阅