Spring 学习笔记《注解》Spring Boot + SpringMVC + JSP + Mybatis 完整Demo

Spring 学习笔记

Spring Boot 学习笔记《使用 Spring Initializer 创建项目》 的基础上进行。(其源码文件包含了本篇的内容)
要测试注解得先有地方用不是,所以要做点准备工作:
1、集成 mybatis
2、添加 service 、mapper、entity
3、Spring 和 mybatis 的扫描都是在启动类上注解配置的
4、数据库添加测试数据
5、修改下样式表
6、修改下 welcome.jsp
7、开始注解(其实上面2、3步的时候顺便就已经加了。哈哈哈哈哈)

注解介绍

Spring

创建 bean

这三个功能相同,名字是为了便于区分所属。默认类名首字小写为 beanid

  • @Component 用于 POJO
  • @Service 用于服务层
  • @Controller 用于控制层

依赖注入

  • @AutoWire 要需要依赖注入的属性上声明。默认按 byType 注入
  • @Resource 要需要依赖注入的属性上声明。默认注入 byName 失败再 byType
  • @Value 从配置文件读取的数据,进行注入 (所以它需要扫描配置文件)
    用法一 带配置文件(就是扫描配置文件的那个bean的id : configProperties)
    编不下去了,这个我还没用过。。。。

Spring Boot

  • @EnableAutoConfiguration 启用Spring引导的自动配置机制(按默认配置给你配)
  • @ComponentScan 默认扫描启用类所在包及其所有子包,也可以给参数指定 @ComponentScan(basePackages = {“com.jerry”}) // spring 扫描包
  • @Configuration 把当前作为配置类,有配置往这来
  • @SpringBootApplication 集齐以上三个注解可以合成 @SpringBootApplication

mybatis

  • @MapperScan("com.jerry.springbootdemo.mapper") // mybatis mapper 包类路径

干活

添加别名扫描的包(POJO包)

/springbootdemo/src/main/resources/application.properties
最后一行

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/jerry?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root

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

mybatis.typeAliasesPackage=com.jerry.springbootdemo.entity 

以前配置 applicationContext.xml 时是这样的:(举例说明,非完整配置)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"

	default-autowire="byName">
	
	<!-- 采用注释的方式配置bean -->
	<context:annotation-config />
	<!-- 配置要扫描的包 -->
	<context:component-scan base-package="com.jerry" />

	<!-- 数据源配置 -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>
	
	<!-- 配置mybitas SqlSessionFactoryBean -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:config/mybatis.xml" />
		<property name="mapperLocations" value="classpath*:/com/jerry/*/mapper/*Mapper.xml" />
		<property name="typeAliasesPackage" value="com.jerry.springbootdemo.entity;" />
	</bean>
	
	<!-- 指定DAO层 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.jerry.*.mapper" />
	</bean>
</beans>

启动类添加注解

/springbootdemo/src/main/java/com/jerry/springbootdemo/SpringbootdemoApplication.java

package com.jerry.springbootdemo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@MapperScan("com.jerry.springbootdemo.mapper")// mybatis mapper 包类路径
public class SpringbootdemoApplication {

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

}

添加测试数据

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for poem
-- ----------------------------
DROP TABLE IF EXISTS `poem`;
CREATE TABLE `poem` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  `title` varchar(16) NOT NULL COMMENT '诗词标题',
  `content` varchar(255) NOT NULL COMMENT '诗词内容',
  `author` varchar(16) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of poem
-- ----------------------------
INSERT INTO `poem` VALUES ('1', '痴情癫', '<p>多情黯叹痴情癫,痴情苦笑多情难。</p><p>相思自古无良药,从来独步赴黄泉。</p', '笑虾');
INSERT INTO `poem` VALUES ('2', '爱云说', '<p>一壶泪,暗淡醇香味。</p><p>化作万樽与谁对?</p><p>忧举杯,乐举杯,地老天荒只一醉。</p><p>欲哭时,男儿无泪。</p><p>千般相思苦。</p><p>杯中汇...</p>', '笑虾');

实体类

/springbootdemo/src/main/java/com/jerry/springbootdemo/entity/Poem.java

package com.jerry.springbootdemo.entity;

import org.springframework.stereotype.Component;

/**
 * poem 表实体类 
 * @author jerryjin 2019-01-24
 */
public class Poem {
    /** 主键 */
    private Long id;

    /** 诗词标题 */
    private String title;

    /** 诗词内容 */
    private String content;

    private String author;

    /**
     * 获取:主键
     * @return id 主键
     */
    public Long getId() {
        return id;
    }

    /**
     * 设置:主键
     * @param id 主键
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * 获取:诗词标题
     * @return title 诗词标题
     */
    public String getTitle() {
        return title;
    }

    /**
     * 设置:诗词标题
     * @param title 诗词标题
     */
    public void setTitle(String title) {
        this.title = title == null ? null : title.trim();
    }

    /**
     * 获取:诗词内容
     * @return content 诗词内容
     */
    public String getContent() {
        return content;
    }

    /**
     * 设置:诗词内容
     * @param content 诗词内容
     */
    public void setContent(String content) {
        this.content = content == null ? null : content.trim();
    }

    /**
     * 获取:
     * @return author 
     */
    public String getAuthor() {
        return author;
    }

    /**
     * 设置:
     * @param author 
     */
    public void setAuthor(String author) {
        this.author = author == null ? null : author.trim();
    }
}

mapper

/springbootdemo/src/main/java/com/jerry/springbootdemo/mapper/PoemMapper.java

package com.jerry.springbootdemo.mapper;

import com.jerry.springbootdemo.entity.Poem;

public interface PoemMapper {
    int deleteByPrimaryKey(Long id);

    int insert(Poem record);

    int insertSelective(Poem record);

    Poem selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(Poem record);

    int updateByPrimaryKey(Poem record);
}

/springbootdemo/src/main/java/com/jerry/springbootdemo/mapper/PoemMapper.xml

<?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.jerry.springbootdemo.mapper.PoemMapper">
  <resultMap id="BaseResultMap" type="com.jerry.springbootdemo.entity.Poem">
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="title" jdbcType="VARCHAR" property="title" />
    <result column="content" jdbcType="VARCHAR" property="content" />
    <result column="author" jdbcType="VARCHAR" property="author" />
  </resultMap>
  <sql id="Base_Column_List">
    id, title, content, author
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from poem
    where id = #{id,jdbcType=BIGINT}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
    delete from poem
    where id = #{id,jdbcType=BIGINT}
  </delete>
  <insert id="insert" parameterType="com.jerry.springbootdemo.entity.Poem">
    insert into poem (id, title, content, 
      author)
    values (#{id,jdbcType=BIGINT}, #{title,jdbcType=VARCHAR}, #{content,jdbcType=VARCHAR}, 
      #{author,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.jerry.springbootdemo.entity.Poem">
    insert into poem
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="title != null">
        title,
      </if>
      <if test="content != null">
        content,
      </if>
      <if test="author != null">
        author,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=BIGINT},
      </if>
      <if test="title != null">
        #{title,jdbcType=VARCHAR},
      </if>
      <if test="content != null">
        #{content,jdbcType=VARCHAR},
      </if>
      <if test="author != null">
        #{author,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.jerry.springbootdemo.entity.Poem">
    update poem
    <set>
      <if test="title != null">
        title = #{title,jdbcType=VARCHAR},
      </if>
      <if test="content != null">
        content = #{content,jdbcType=VARCHAR},
      </if>
      <if test="author != null">
        author = #{author,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.jerry.springbootdemo.entity.Poem">
    update poem
    set title = #{title,jdbcType=VARCHAR},
      content = #{content,jdbcType=VARCHAR},
      author = #{author,jdbcType=VARCHAR}
    where id = #{id,jdbcType=BIGINT}
  </update>
</mapper>

服务层

/springbootdemo/src/main/java/com/jerry/springbootdemo/service/IPoemService.java

package com.jerry.springbootdemo.service;

import com.jerry.springbootdemo.entity.Poem;

public interface IPoemService {
	Poem getById(Long id);

	Long save(Poem record);

	Long saveAll(Poem record);

    int delById(Long id);
}

/springbootdemo/src/main/java/com/jerry/springbootdemo/service/impl/PoemService.java

package com.jerry.springbootdemo.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.jerry.springbootdemo.entity.Poem;
import com.jerry.springbootdemo.mapper.PoemMapper;
import com.jerry.springbootdemo.service.IPoemService;

@Service
public class PoemService implements IPoemService {

	//-------------------------------------------------------
	@Resource
	private PoemMapper poemMapper;
	
	//-------------------------------------------------------
	@Override
	public Poem getById(Long id) {
		return poemMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public Long saveAll(Poem record) {
		if(record.getId() == null){
			poemMapper.insert(record);
		}else{
			poemMapper.updateByPrimaryKey(record);
		}
		return record.getId();
	}

	@Override
	public Long save(Poem record) {
		if(record.getId() == null){
			poemMapper.insertSelective(record);
		}else{
			poemMapper.updateByPrimaryKeySelective(record);
		}
		return record.getId();
	}

	@Override
	public int delById(Long id) {
		return poemMapper.deleteByPrimaryKey(id);
	}
	
	//-----------------------------------------------------------------
	

}

控制层

/springbootdemo/src/main/java/com/jerry/springbootdemo/controller/WelcomeController.java

package com.jerry.springbootdemo.controller;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jerry.springbootdemo.service.IPoemService;

@Controller
public class WelcomeController {

	@Resource
	private IPoemService poemService;
	
	@RequestMapping("/")
	public String welcome(Map<String, Object> model) {
		model.put("name", "笨笨");
		model.put("poem", poemService.getById(1L));
		return "welcome";
	}
}

样式表

/springbootdemo/src/main/resources/static/css/main.css

h1 {
	color: #03a9f4;
}

.poem {
    color: #607D8B;
}

.poem .title {
    font-size: 2.5em;
}

.poem .author {
    font-size: 1.0em;
}

.poem .content p {
    font-size: 1.5em;
}

JSP

/springbootdemo/src/main/webapp/WEB-INF/jsp/welcome.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<link href="/css/main.css" rel="stylesheet" />
	</head>
	<body>
		<div class="container">
			<div class="starter-template">
				<h1>大家好,我是${name},${name}的笨,${name}的笨,谢谢!</h1>
				<div class="poem">
					<p><span class="title">${poem.title}</span><span class="author"> —— ${poem.author}</span></p>
					<div class="content">${poem.content} </div>
				</div>
			</div>
		</div>
	</body>
</html>

看看效果

在这里插入图片描述

源码下载

https://download.csdn.net/download/jx520/10935659

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笑虾

多情黯叹痴情癫。情癫苦笑多情难

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值