mybatis xml 写法解析

This commit is contained in:
qiurunze 2018-09-27 22:10:09 +08:00
parent 9c73ca56a5
commit d053fbcf6c
40 changed files with 1136 additions and 671 deletions

View File

@ -11,6 +11,7 @@
</annotationProcessing>
<bytecodeTargetLevel>
<module name="miaosha" target="1.6" />
<module name="springcloud-server" target="1.8" />
</bytecodeTargetLevel>
</component>
</project>

View File

@ -2,5 +2,6 @@
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/springcloud-server" charset="UTF-8" />
</component>
</project>

File diff suppressed because it is too large Load Diff

View File

@ -122,3 +122,7 @@ redis的数量不是库存,他的作用仅仅只是为了阻挡多余的请求
注意:局部变量是同步或局部线程的一个好的替代,它总是能够保证线程安全。唯一可能限制你这样做的是你的应用设计约束<br>
所以设计threadlocal存储user不会对对象产生影响每次进来一个请求都会产生自身的线程变量来存储
### <font color=#0099ff size=3 >15.mybatis如何使用注解与xml配置</font><br>
本文使用的是注解方法开发所以不做过多解释<br>
下面仔细讲解以下如何详细使用xml开发<br>

0
gitignore Normal file
View File

10
pom.xml
View File

@ -96,7 +96,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies>
<build>
@ -107,5 +106,14 @@
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>

View File

@ -1,15 +1,30 @@
package com.geekq.miaosha;
import com.geekq.miaosha.domain.MiaoshaUser;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.Reader;
/**
* mybatis xml 写法的配置测试类
*/
public class Test {
public static void main(String[] args) {
DemoTask demoTask = new DemoTask();
DemoTask demoTask1 = new DemoTask();
DemoTask demoTask2 = new DemoTask();
Thread t = new Thread(demoTask);
t.start();
new Thread(demoTask).start();
new Thread(demoTask2).start();
public static void main(String[] args) throws IOException {
//读取配置文件
Reader reader = Resources.getResourceAsReader("config.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sessionFactory.openSession();
String statement = "com.geekq.miaosha.dao.UserMapper.getMiaoShaUserById" ;
MiaoshaUser user = session.selectOne(statement,"18612766134");
System.out.println(user.toString());
}
}

View File

@ -0,0 +1,27 @@
package com.geekq.miaosha.common;
/**
* 响应类
*/
public enum ResponseCode {
SUCCESS(0, "SUCCESS"),
ERROR(1, "ERROR"),
NEED_LOGIN(10, "NEED_LOGIN"),
ILLEGAL_ARGUMENT(2, "ILLEGAL_ARGUMENT");
private final int code;
private final String desc;
private ResponseCode(int code, String desc) {
this.code = code;
this.desc = desc;
}
public int getCode() {
return code;
}
public String getDesc() {
return desc;
}
}

View File

@ -0,0 +1,78 @@
package com.geekq.miaosha.common;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.io.Serializable;
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
//保证序列化的时候 不会有空
public class ServerResponse<T> implements Serializable {
private int status ;
private String msg ;
private T data ;
private ServerResponse( int status ){
this.status =status;
}
private ServerResponse( int status ,T data){
this.status =status;
this.data = data;
}
private ServerResponse( int status ,String msg ,T data){
this.status =status;
this.msg = msg ;
this.data = data;
}
private ServerResponse( int status ,String msg ){
this.status =status;
this.msg = msg ;
}
@JsonIgnore
public boolean isSuccess(){
return this.status == ResponseCode.SUCCESS.getCode();
}
public int getStatus() {
return status;
}
public String getMsg() {
return msg;
}
public T getData() {
return data;
}
public static <T> ServerResponse<T> createBySuccess(){
return new ServerResponse<T>(ResponseCode.SUCCESS.getCode());
}
public static <T> ServerResponse<T> createBySuccessMessage(String msg){
return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg);
}
public static <T> ServerResponse<T> createBySuccess(T data){
return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),data);
}
public static <T> ServerResponse<T> createBySuccess(String msg,T data){
return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg,data);
}
public static <T> ServerResponse<T> createByError(){
return new ServerResponse<T>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc());
}
public static <T> ServerResponse<T> createByErrorMessage(String errorMsg){
return new ServerResponse<T>(ResponseCode.ERROR.getCode(),errorMsg);
}
public static <T> ServerResponse<T> createByErrorCodeMessage(int errorCode , String errorMsg){
return new ServerResponse<T>(errorCode,errorMsg);
}
}

View File

@ -1,14 +1,17 @@
package com.geekq.miaosha.controller;
import com.geekq.miaosha.result.CodeMsg;
import com.geekq.miaosha.dao.UserMapper;
import com.geekq.miaosha.domain.MiaoshaUser;
import com.geekq.miaosha.result.Result;
import com.geekq.miaosha.service.MiaoShaUserService;
import com.geekq.miaosha.vo.LoginVo;
import org.apache.ibatis.annotations.Mapper;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
@ -24,6 +27,9 @@ public class LoginController {
private MiaoShaUserService userService;
@Autowired
private UserMapper userMapper;
@RequestMapping("/to_login")
public String tologin(LoginVo loginVo) {
log.info(loginVo.toString());
@ -38,4 +44,31 @@ public class LoginController {
return Result.success(true);
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public Result<String> register(MiaoshaUser user) {
return userService.insertMiaoShaUser(user);
}
@RequestMapping("/mybatis")
public void mybatisXml() {
//
int count = userMapper.getMiaoShaUserNum();
System.out.println(count);
MiaoshaUser user = userMapper.getMiaoShaUserById(Long.valueOf("18612766134"));
System.out.println(user);
//
// MiaoshaUser miaoshaUser =new MiaoshaUser();
// miaoshaUser.setId(Long.valueOf("1234569879"));
// miaoshaUser.setNickname("test");
// Long num = userMapper.insertMiaoShaUser(miaoshaUser);
MiaoshaUser upmiaoshaUser =new MiaoshaUser();
upmiaoshaUser.setId(Long.valueOf("1234569879"));
upmiaoshaUser.setNickname("test1");
userMapper.updateMiaoShaUser(upmiaoshaUser);
userMapper.deleteMiaoShaUser(Long.valueOf("1234569879"));
}
}

View File

@ -0,0 +1,24 @@
package com.geekq.miaosha.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/user/")
public class UserController {
/**
* 用户登录
* @param username
* @param password
* @param session
* @return
*/
@RequestMapping(value = "/login",method = RequestMethod.POST)
public Object login(String username , String password , HttpSession session){
return null;
}
}

View File

@ -1,10 +1,7 @@
package com.geekq.miaosha.dao;
import com.geekq.miaosha.domain.MiaoshaUser;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.*;
@Mapper
public interface MiaoShaUserDao {
@ -15,4 +12,9 @@ public interface MiaoShaUserDao {
@Update("update miaosha_user set password = #{password} where id = #{id}")
public void update(MiaoshaUser toBeUpdate);
@Insert("insert into miaosha_user (id , nickname ,password , salt ,head,register_date,last_login_date)value (#{id},#{nickname},#{password},#{salt},#{nickname},#{head},#{register_date},#{last_login_date}) ")
public long insertMiaoShaUser(MiaoshaUser miaoshaUser);
}

View File

@ -1,13 +0,0 @@
package com.geekq.miaosha.dao;
import com.geekq.miaosha.domain.MiaoshaUser;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface MiaoshaUserDao {
@Select("select * from miaosha_user where id = #{id}")
public MiaoshaUser getById(@Param("id") long id);
}

View File

@ -0,0 +1,30 @@
package com.geekq.miaosha.dao;
import com.geekq.miaosha.domain.MiaoshaUser;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* mybatis xml 写法
*/
@Mapper
public interface UserMapper {
int countbyMenuId();
MiaoshaUser getMiaoShaUserById(Long phoneId);
//秒杀对象获取 mybatis的#与$的区别
List<MiaoshaUser> queryMiaoShaUserOrderByColumn(String column);
//查询总条数
public int getMiaoShaUserNum();
public Long insertMiaoShaUser(MiaoshaUser user);
//更改表数据
void updateMiaoShaUser(MiaoshaUser user) ;
//删除表数据
void deleteMiaoShaUser(long id );
}

View File

@ -59,4 +59,18 @@ public class MiaoshaUser {
public void setLoginCount(Integer loginCount) {
this.loginCount = loginCount;
}
@Override
public String toString() {
return "MiaoshaUser{" +
"id=" + id +
", nickname='" + nickname + '\'' +
", password='" + password + '\'' +
", salt='" + salt + '\'' +
", head='" + head + '\'' +
", registerDate=" + registerDate +
", lastLoginDate=" + lastLoginDate +
", loginCount=" + loginCount +
'}';
}
}

View File

@ -7,6 +7,11 @@ public class CodeMsg {
//通用的错误码
public static CodeMsg SUCCESS = new CodeMsg(0, "success");
public static CodeMsg SUCCESS_RESIGETER = new CodeMsg(200,"注册成功!");
public static CodeMsg RESIGETER_FAIL = new CodeMsg(300,"注册失败!");
public static CodeMsg SERVER_ERROR = new CodeMsg(500100, "服务端异常");
public static CodeMsg BIND_ERROR = new CodeMsg(500101, "参数校验异常:%s");
public static CodeMsg REQUEST_ILLEGAL = new CodeMsg(500102, "请求非法");

View File

@ -8,6 +8,7 @@ public class Result<T> {
/**
* 成功时候的调用
*
* @param data
* @param <T>
* @return
@ -16,8 +17,23 @@ public class Result<T> {
return new Result<T>(data);
}
/**
* 注册时候调用
*
* @param msg
* @param data
* @param <T>
* @return
*/
public static <T> Result<T> success(CodeMsg msg) {
return new Result<T>(CodeMsg.SUCCESS_RESIGETER);
}
/**
* 失败的时候调用
*
* @param cm
* @param <T>
* @return
@ -26,6 +42,11 @@ public class Result<T> {
return new Result<T>(cm);
}
// public Result(CodeMsg msg, T data) {
// this.code = msg.getCode();
// this.msg = msg.getMsg();
// this.data = data;
// }
private Result(CodeMsg cm) {
if (cm == null) {

View File

@ -0,0 +1,7 @@
package com.geekq.miaosha.service;
public interface IUserService {
Object login(String username , String password) ;
}

View File

@ -7,8 +7,10 @@ import com.geekq.miaosha.exception.GlobleException;
import com.geekq.miaosha.redis.MiaoShaUserKey;
import com.geekq.miaosha.redis.RedisService;
import com.geekq.miaosha.result.CodeMsg;
import com.geekq.miaosha.result.Result;
import com.geekq.miaosha.utils.UUIDUtil;
import com.geekq.miaosha.vo.LoginVo;
import com.sun.org.apache.bcel.internal.classfile.Code;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -74,6 +76,17 @@ public class MiaoShaUserService {
return true;
}
public Result<String> insertMiaoShaUser(MiaoshaUser miaoshaUser){
long resultRegister = miaoShaUserDao.insertMiaoShaUser(miaoshaUser);
if(resultRegister == 0){
throw new GlobleException(CodeMsg.RESIGETER_FAIL);
}
return Result.success(CodeMsg.SUCCESS_RESIGETER);
}
public boolean login(HttpServletResponse response , LoginVo loginVo) {
if(loginVo ==null){
throw new GlobleException(CodeMsg.SERVER_ERROR);

View File

@ -8,10 +8,13 @@ spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
#mybatis
mybatis.type-aliases-package=com.imooc.miaosha.domain
mybatis.type-aliases-package=com.geekq.miaosha.domain
#开启驼峰转换
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.mapperLocations = classpath:com/imooc/miaosha/dao/*.xml
#mybatis.mapperLocations = classpath:com/geekq/miaosha/dao/*.xml
mybatis.mapperLocations=classpath:mybatis/mapper/*.xml
#add mybatis
mybatis.config-locations=classpath:mybatis/config.xml
#datasource
spring.datasource.url=jdbc:mysql://localhost:3306/miaosha?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false
spring.datasource.username=root

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="miaoshauser1" type="com.geekq.miaosha.domain.MiaoshaUser"/>
</typeAliases>
<!-- <mappers>
<mapper resource="/mybatis/mapper/UserMapper.xml"></mapper>
</mappers>-->
</configuration>

View File

@ -0,0 +1,62 @@
<?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.geekq.miaosha.dao.UserMapper">
<!--结果集映射-->
<resultMap id="BaseResultMap" type="com.geekq.miaosha.domain.MiaoshaUser">
<id column="id" property="id" jdbcType="BIGINT"/>
<result column="nickname" property="nickname" jdbcType="VARCHAR"/>
<result column="salt" property="salt" jdbcType="VARCHAR"/>
<result column="head" property="head" jdbcType="VARCHAR"/>
<result column="register_date" property="registerDate" jdbcType="TIMESTAMP"/>
<result column="last_login_date" property="lastLoginDate" jdbcType="TIMESTAMP"/>
<result column="login_Count" property="loginCount" jdbcType="INTEGER"/>
</resultMap>
<!--增加一条数据-->
<insert id="insertMiaoShaUser" parameterType="com.geekq.miaosha.domain.MiaoshaUser" keyProperty="id">
insert into miaosha_user (id, nickname, salt, register_date,last_login_date,login_Count ) values
(#{id,jdbcType=BIGINT},#{nickname,jdbcType=VARCHAR},
#{salt,jdbcType=VARCHAR},#{registerDate,jdbcType=DATE},#{lastLoginDate,jdbcType=DATE},
#{loginCount,jdbcType=INTEGER}
)
</insert>
<!--更新一条数据-->
<update id="updateMiaoShaUser" >
update miaosha_user set nickname = #{nickname},
login_Count = #{loginCount}
where id=#{id}
</update>
<!--删除一条数据-->
<delete id="deleteMiaoShaUser" parameterType="Long">
delete from miaosha_user
where id = #{id,jdbcType=BIGINT}
</delete>
<sql id="Base_Column_List"> id, nickname, salt, register_date,last_login_date,login_Count </sql>
<select id="getMiaoShaUserById" parameterType="LONG" resultType="miaoshauser">
SELECT
<include refid="Base_Column_List"/>
FROM miaosha_user WHERE id = #{id}
</select>
<select id="getMiaoShaUserNum" resultType="int">
select count(*) from miaosha_user
</select>
<select id="countbyMenuId" parameterType="java.lang.Integer"
resultType="java.lang.Integer"> select count(*) from miaosha_user
</select>
</mapper>

View File

@ -8,10 +8,13 @@ spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
#mybatis
mybatis.type-aliases-package=com.imooc.miaosha.domain
mybatis.type-aliases-package=com.geekq.miaosha.domain
#开启驼峰转换
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.mapperLocations = classpath:com/imooc/miaosha/dao/*.xml
#mybatis.mapperLocations = classpath:com/geekq/miaosha/dao/*.xml
mybatis.mapperLocations=classpath:mybatis/mapper/*.xml
#add mybatis
mybatis.config-locations=classpath:mybatis/config.xml
#datasource
spring.datasource.url=jdbc:mysql://localhost:3306/miaosha?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false
spring.datasource.username=root

Binary file not shown.

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="miaoshauser1" type="com.geekq.miaosha.domain.MiaoshaUser"/>
</typeAliases>
<!-- <mappers>
<mapper resource="/mybatis/mapper/UserMapper.xml"></mapper>
</mappers>-->
</configuration>

View File

@ -0,0 +1,62 @@
<?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.geekq.miaosha.dao.UserMapper">
<!--结果集映射-->
<resultMap id="BaseResultMap" type="com.geekq.miaosha.domain.MiaoshaUser">
<id column="id" property="id" jdbcType="BIGINT"/>
<result column="nickname" property="nickname" jdbcType="VARCHAR"/>
<result column="salt" property="salt" jdbcType="VARCHAR"/>
<result column="head" property="head" jdbcType="VARCHAR"/>
<result column="register_date" property="registerDate" jdbcType="TIMESTAMP"/>
<result column="last_login_date" property="lastLoginDate" jdbcType="TIMESTAMP"/>
<result column="login_Count" property="loginCount" jdbcType="INTEGER"/>
</resultMap>
<!--增加一条数据-->
<insert id="insertMiaoShaUser" parameterType="com.geekq.miaosha.domain.MiaoshaUser" keyProperty="id">
insert into miaosha_user (id, nickname, salt, register_date,last_login_date,login_Count ) values
(#{id,jdbcType=BIGINT},#{nickname,jdbcType=VARCHAR},
#{salt,jdbcType=VARCHAR},#{registerDate,jdbcType=DATE},#{lastLoginDate,jdbcType=DATE},
#{loginCount,jdbcType=INTEGER}
)
</insert>
<!--更新一条数据-->
<update id="updateMiaoShaUser" >
update miaosha_user set nickname = #{nickname},
login_Count = #{loginCount}
where id=#{id}
</update>
<!--删除一条数据-->
<delete id="deleteMiaoShaUser" parameterType="Long">
delete from miaosha_user
where id = #{id,jdbcType=BIGINT}
</delete>
<sql id="Base_Column_List"> id, nickname, salt, register_date,last_login_date,login_Count </sql>
<select id="getMiaoShaUserById" parameterType="LONG" resultType="miaoshauser">
SELECT
<include refid="Base_Column_List"/>
FROM miaosha_user WHERE id = #{id}
</select>
<select id="getMiaoShaUserNum" resultType="int">
select count(*) from miaosha_user
</select>
<select id="countbyMenuId" parameterType="java.lang.Integer"
resultType="java.lang.Integer"> select count(*) from miaosha_user
</select>
</mapper>