上篇演示了Spring Boot最简单的一个实例,这篇将整合mysql和mybatis实现简单的登录功能。
以前我们写java代码,都要自己手动一个一个去建实体类,写方法,这种琐碎的事情不但无聊且浪费时间,这里介绍一个好用的工具,Mybatis-Generator。它可以自动生成Dao、Modle、Mapping相关文件,具体使用方法请参考:http://www.cnblogs.com/lichenwei/p/4145696.html
将自动生成的文件拖到建好的Spring Boot项目中
接着引入mysql、mybatis相关依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
然后新建application.yml文件,将原来的application.properties文件删除,在application.yml中写入:
server:
port: 8080
spring:
datasource:
name: test
url: jdbc:mysql://127.0.0.1:3306/test
username: root
password: root
## 该配置节点为独立的节点,有很多同学容易将这个配置放在spring的节点下,导致配置无法被识别
mybatis:
mapper-locations: classpath:mapper/*.xml #注意:一定要对应mapper映射xml文件的所在路径
type-aliases-package: com.example.model # 注意:对应实体类的路径
要根据自己的实际情况修改相应配置,避免直接复制粘贴造成项目报错。
接着在templates下新建login.html:
<!DOCTYPE html>
<html>
<head>
<title>登录</title>
<meta name="keywords" content="keyword1,keyword2,keyword3"/>
<meta name="description" content="this is my page"/>
<meta name="content-type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="../js/jquery.min.js"></script>
</head>
<body>
<form id="myForm">
用户名:<input type="text" id="username" name="username" /><br/>
密码:<input type="password" id="password" name="password" /><br/>
<button type="button" id="submit">登录</button>
</form>
</body>
<script type="text/javascript">
$("#submit").click(function(){
$.ajax({
url:"getUser",
data:$("#myForm").serialize(),
type:"POST",
dataType:"json",
success:function(data){
if(data.msg == "1"){
alert("登录成功!");
window.location.href="index";
}else{
alert("登录失败!");
}
},
erro:function(){
alert("fail");
}
})
})
</script>
</html>
其中jquery文件放在static文件下,引用时要注意。另外这里扯一句,避免其他人和我踩一样的坑,在这里用ajax提交整个表单时,如果采用button标签,必须在标签里加上type="button",不然这里还会默认为input标签的submit类型,也就是说在ajax提交一次后,表单的submit还会再提交一次,所以这里必须加上type="button",切记切记。
查询语句和Dao层、Service层代码不做赘述,直接贴代码:
UserMapper.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.example.dao.UserDao">
<resultMap id="BaseResultMap" type="com.example.model.User">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
-->
<id column="id" jdbcType="INTEGER" property="id" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="sex" jdbcType="VARCHAR" property="sex" />
<result column="photo" jdbcType="VARCHAR" property="photo" />
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
-->
id, username, email, password, sex, photo
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
-->
select
<include refid="Base_Column_List" />
from t_user
where id = #{id,jdbcType=INTEGER}
</select>
<!-- 根据用户名和密码查找用户 -->
<select id="getUserByNameAndPwd" resultMap="BaseResultMap">
select id,username,email,sex from t_user
<where>
<if test="username != null and username != ''">
and username = #{username}
</if>
<if test="password != null and password != ''">
and password = #{password}
</if>
</where>
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
-->
delete from t_user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.example.model.User">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
-->
insert into t_user (id, username, email,
password, sex, photo
)
values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, #{photo,jdbcType=VARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="com.example.model.User">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
-->
insert into t_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="username != null">
username,
</if>
<if test="email != null">
email,
</if>
<if test="password != null">
password,
</if>
<if test="sex != null">
sex,
</if>
<if test="photo != null">
photo,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="username != null">
#{username,jdbcType=VARCHAR},
</if>
<if test="email != null">
#{email,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="sex != null">
#{sex,jdbcType=VARCHAR},
</if>
<if test="photo != null">
#{photo,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.example.model.User">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
-->
update t_user
<set>
<if test="username != null">
username = #{username,jdbcType=VARCHAR},
</if>
<if test="email != null">
email = #{email,jdbcType=VARCHAR},
</if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
</if>
<if test="sex != null">
sex = #{sex,jdbcType=VARCHAR},
</if>
<if test="photo != null">
photo = #{photo,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.example.model.User">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
-->
update t_user
set username = #{username,jdbcType=VARCHAR},
email = #{email,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
sex = #{sex,jdbcType=VARCHAR},
photo = #{photo,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
UserDao.java
package com.example.dao;
import java.util.Map;
import com.example.model.User;
public interface UserDao {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_user
*
* @mbg.generated
*/
int deleteByPrimaryKey(Integer id);
/**
* 根据用户名和密码查找用户
* @param params
* @return
*/
User getUserByNameAndPwd(Map<String,Object> params);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_user
*
* @mbg.generated
*/
int insert(User record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_user
*
* @mbg.generated
*/
int insertSelective(User record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_user
*
* @mbg.generated
*/
User selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_user
*
* @mbg.generated
*/
int updateByPrimaryKeySelective(User record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_user
*
* @mbg.generated
*/
int updateByPrimaryKey(User record);
}
UserService.java
package com.example.service;
import java.util.Map;
import com.example.model.User;
public interface UserService {
/**
* 根据用户名和密码查找用户
* @param params
* @return
*/
User getUserByNameAndPwd(Map<String,Object> params);
}
UserServiceImpl.java
package com.example.service.impl;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.dao.UserDao;
import com.example.model.User;
import com.example.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public User getUserByNameAndPwd(Map<String, Object> params) {
return userDao.getUserByNameAndPwd(params);
}
}
UserController.java
package com.example.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.model.User;
import com.example.service.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/index")
public String index(){
return "index";
}
@RequestMapping("/login")
public String login(){
return "login";
}
@RequestMapping("/getUser")
@ResponseBody
public Map<String,Object> getUser(@RequestParam Map<String,Object> params){
Map<String,Object> map = new HashMap<String, Object>();
User user = userService.getUserByNameAndPwd(params);
if(user != null){
map.put("msg", "1");
}else{
map.put("msg", "0");
}
return map;
}
}
最后,在Application中添加MapperScan,动态扫描
package com.example;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.dao")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
System.out.println("(*^▽^*)启动成功!(〃'▽'〃)");
}
}
启动服务后,在浏览器中输入 http://localhost:8080/user/login