Mybatis系列(四)注解
Mybatis系列(四)注解
1.pom.xlm:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId>
<artifactId>spring-mybatis_zhujie</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>spring-mybatis</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
2.application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver server.port=8081
3.mybatis-config-local.xml:
<?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>
<!-- 引入外部配置文件 -->
<properties resource="application.properties"></properties>
<!-- 配置mybatis运行环境 -->
<environments default="cybatis">
<environment id="master">
<!-- type="JDBC" 代表使用JDBC的提交和回滚来管理事务 -->
<transactionManager type="JDBC" />
<!-- mybatis提供了3种数据源类型,分别是:POOLED,UNPOOLED,JNDI -->
<!-- POOLED 表示支持JDBC数据源连接池 -->
<!-- UNPOOLED 表示不支持数据源连接池 -->
<!-- JNDI 表示支持外部数据源连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${spring.datasource.driver-class-name}" />
<property name="url" value="${spring.datasource.url}" />
<property name="username" value="${spring.datasource.username}" />
<property name="password" value="${spring.datasource.password}" />
</dataSource>
</environment>
<environment id="slave">
<!-- type="JDBC" 代表使用JDBC的提交和回滚来管理事务 -->
<transactionManager type="JDBC" />
<!-- mybatis提供了3种数据源类型,分别是:POOLED,UNPOOLED,JNDI -->
<!-- POOLED 表示支持JDBC数据源连接池 -->
<!-- UNPOOLED 表示不支持数据源连接池 -->
<!-- JNDI 表示支持外部数据源连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/user" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper class = "com.example.mybatisZhuJie.dao.UserDao"/>
</mappers>
</configuration>
4.User:
package com.example.mybatisZhuJie.entity; public class User {
private int id;
private String user_name;
private String password;
private int age; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getUser_name() {
return user_name;
} public void setUser_name(String user_name) {
this.user_name = user_name;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} @Override
public String toString() {
return "User{" +
"id=" + id +
", user_name='" + user_name + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
}
5.UserDao:
package com.example.mybatisZhuJie.dao; import com.example.mybatisZhuJie.entity.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select; import java.util.ArrayList; public interface UserDao {
@Select("select id, user_name ,password, age from user_t")
public ArrayList<User> selectAll(); @Insert("insert into user_t(id, user_name ,password, age) values(#{id},#{user_name}, #{password}, #{age})")
public int insert(User user); @Delete("delete from user_t where id =#{id}")
public int delete(@Param("id") int id); //Sql语句进行分页
@Select("select id, user_name ,password, age from user_t limit #{currPage}, #{pageSize}")
public ArrayList<User> queryStudentsBySql(@Param("currPage") int currPage, @Param("pageSize") int pageSize);
}
6.UserDaoIml:
package com.example.mybatisZhuJie.dao; import com.example.mybatisZhuJie.entity.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory; import java.util.ArrayList; public class UserDaoIml implements UserDao { private SqlSessionFactory sessionFactory; public UserDaoIml(SqlSessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
} public ArrayList<User> selectAll() {
ArrayList<User> users = new ArrayList<>();
SqlSession sqlSession = null;
try{
sqlSession = sessionFactory.openSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
users = userDao.selectAll();
return users;
} catch (Exception e) {
e.printStackTrace();
return users;
}
} public int insert(User user) {
SqlSession sqlSession = null;
int count = 0;
try{
sqlSession = sessionFactory.openSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
count = userDao.insert(user);
if( count > 0) {
sqlSession.commit();
}
return count;
} catch (Exception e) {
e.printStackTrace();
return count;
}
} public int delete(int id) {
SqlSession sqlSession = null;
int count = 0;
try{
sqlSession = sessionFactory.openSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
count = userDao.delete(id);
if( count > 0) {
sqlSession.commit();
}
return count;
} catch (Exception e) {
e.printStackTrace();
return count;
}
} public ArrayList<User> queryStudentsBySql(@Param("currPage") int currPage, @Param("pageSize") int pageSize) {
ArrayList<User> users = new ArrayList<>();
SqlSession sqlSession = null;
try{
sqlSession = sessionFactory.openSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
users = userDao.queryStudentsBySql(currPage, pageSize);
return users;
} catch (Exception e) {
e.printStackTrace();
return users;
}
}
}
7.springboot启动项:
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.concurrent.TimeoutException; @SpringBootApplication
public class SpringBootAll { private static String env = "local";
public static SqlSessionFactory sqlSessionFactory; public static void main(String[] args) throws Exception{
new SpringBootAll().init();
SpringApplication.run(SpringBootAll.class, args);
} public void init() throws Exception{
//初始化数据库-单个数据库
initMySql();
} /**
* 单个数据库
*/
private void initMySql(){
try{
String resource = String.format("mybatis-config-%s.xml", SpringBootAll.env);
Reader reader = Resources.getResourceAsReader(resource);
SpringBootAll.sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
}
8.controller:
package com.example.mybatisZhuJie.controller; import com.example.mybatisZhuJie.AppZhuJie;
import com.example.mybatisZhuJie.dao.UserDao;
import com.example.mybatisZhuJie.dao.UserDaoIml;
import com.example.mybatisZhuJie.entity.User;
import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; @RestController
public class UserController { UserDao userDao = new UserDaoIml(SpringBootAll.sqlSessionFactory); @RequestMapping(value = "/map", method = RequestMethod.GET)
@ResponseBody
public Map<String, Object> getRegTimeByUserId (HttpServletRequest request, HttpServletResponse response) throws Exception{
Map<String, Object> result = new HashMap<String, Object>();
String data = request.getParameter("data");
result.put("data",data);
result.put("code","200");
return result;
} @RequestMapping(value = "/select/all", method = RequestMethod.GET)
@ResponseBody
public List<User> selectAll(HttpServletRequest request, HttpServletResponse response) throws Exception{
List<User> users = userDao.selectAll();
return users;
} @RequestMapping(value = "/select/some", method = RequestMethod.GET)
@ResponseBody
public ArrayList<User> selectSome(HttpServletRequest request, HttpServletResponse response
,@RequestParam(value = "start", defaultValue = "0") int start
,@RequestParam(value = "end", defaultValue = "3") int end) throws Exception{
ArrayList<User> users = userDao.queryStudentsBySql(start, end);
return users;
} @RequestMapping(value = "/delete", method = RequestMethod.GET)
@ResponseBody
public String delete(@RequestParam(value = "id", defaultValue = "6") int id) {
int count = userDao.delete(id);
return "成功删除" + count + "条数据!";
} @RequestMapping(value = "/insert", method = RequestMethod.GET)
@ResponseBody
public String insert(@RequestParam(value = "id", defaultValue = "6") int id
, @RequestParam(value = "username", defaultValue = "易水寒")String username
, @RequestParam(value = "password", defaultValue = "yiqq")String password
, @RequestParam(value = "age", defaultValue = "22") int age) {
User user = new User();
user.setId(id);
user.setAge(age);
user.setPassword(password);
user.setUser_name(username);
int count = userDao.insert(user);
return "成功插入" + count + "条数据!";
} @RequestMapping(value = "/hello", method = RequestMethod.GET)
@ResponseBody
public String say(@RequestParam(value = "name", defaultValue = "易水寒") String name) {
return "Hello World: " + name;
} }
9.sql:
CREATE TABLE `user_t` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`user_name` varchar(10) DEFAULT NULL,
`password` varchar(10) DEFAULT NULL,
`age` int(10) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=896 DEFAULT CHARSET=utf8
Mybatis系列(四)注解的更多相关文章
- MyBatis系列四 之 智能标签进行查询语句的拼接
MyBatis系列四 之 智能标签进行查询语句的拼接 使用Foreach进行多条件查询 1.1 foreach使用数组进行多条件查询 在MyBatis的映射文件中进行如下配置 <!--根据数组进 ...
- 深入浅出Mybatis系列四-配置详解之typeAliases别名(mybatis源码篇)
注:本文转载自南轲梦 注:博主 Chloneda:个人博客 | 博客园 | Github | Gitee | 知乎 上篇文章<深入浅出Mybatis系列(三)---配置详解之properties ...
- Mybatis系列(四):Mybatis缓存
一.MyBatis缓存介绍 MyBatis 提供了一级缓存和二级缓存的支持 1. 一级缓存: 默认开启,基于PerpetualCache 的 HashMap本地缓存,其存储作用域为 Se ...
- Spring Boot入门系列(十九)整合mybatis,使用注解实现动态Sql、参数传递等常用操作!
前面介绍了Spring Boot 整合mybatis 使用注解的方式实现数据库操作,介绍了如何自动生成注解版的mapper 和pojo类. 接下来介绍使用mybatis 常用注解以及如何传参数等数据库 ...
- Mybatis系列全解(四):全网最全!Mybatis配置文件XML全貌详解
封面:洛小汐 作者:潘潘 做大事和做小事的难度是一样的.两者都会消耗你的时间和精力,所以如果决心做事,就要做大事,要确保你的梦想值得追求,未来的收获可以配得上你的努力. 前言 上一篇文章 <My ...
- 深入浅出Mybatis系列(四)---配置详解之typeAliases别名(mybatis源码篇)
上篇文章<深入浅出Mybatis系列(三)---配置详解之properties与environments(mybatis源码篇)> 介绍了properties与environments, ...
- Mybatis源码详解系列(四)--你不知道的Mybatis用法和细节
简介 这是 Mybatis 系列博客的第四篇,我本来打算详细讲解 mybatis 的配置.映射器.动态 sql 等,但Mybatis官方中文文档对这部分内容的介绍已经足够详细了,有需要的可以直接参考. ...
- Mybatis系列(四)映射文件
转自:https://blog.csdn.net/chris_mao/article/details/48811507 Mybatis的真正强大,在于她对SQL的映射,这也是她吸引人的地方.实现相同的 ...
- 深入浅出Mybatis系列(五)---TypeHandler简介及配置(mybatis源码篇)
上篇文章<深入浅出Mybatis系列(四)---配置详解之typeAliases别名(mybatis源码篇)>为大家介绍了mybatis中别名的使用,以及其源码.本篇将为大家介绍TypeH ...
随机推荐
- java中File IO流的笔记
1.File文件的属性和操作 boolean exists( ) 判断文件或目录是否存在boolean isFile( ) 判断是否是文件boolean isDirectory( ) 判断是否是目 ...
- 【0802 | Day 7】Python进阶(一)
目 录 数字类型的内置方法 一.整型内置方法(int) 二.浮点型内置方法(float) 字符串类型内置方法 一.字符串类型内置方法(str) 二.常用操作和内置方法 优先掌握: 1.索引取值 2. ...
- 阿里、网易和腾讯面试题 C/C++
一.线程.锁 1.Posix Thread互斥锁 线程锁创建 a.静态创建 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; b.动态创建 pthr ...
- Linux 使用命令 1
fold : Usage: fold [OPTION]... [FILE]...Wrap input lines in each FILE (standard input by default), w ...
- map redcue filter sorted函数
sorted 函数 接收一个key函数来实现自定义的排序 # 训练集和验证集的文件命名不一样 # test1: data/test1/8973.jpg # train: data/train/cat. ...
- mybatis 源码分析(二)mapper 初始化
mybatis 的初始化还是相对比较复杂,但是作者在初始化过程中使用了多种设计模式,包括建造者.动态代理.策略.外观等,使得代码的逻辑仍然非常清晰,这一点非常值得我们学习: 一.mapper 初始化主 ...
- mssql server master 数据库还原
今天想试一下master数据库还原,在进入单用户模式的时候,在命令行输入sqlserver.exe -c -f -m结果显示 'sqlserver.exe' 不是内部或外部命令,也不是可运行的程序或批 ...
- 敏捷开发--必备工具Jira&Confluence学习视频
敏捷开发必备工具:Jira+confluence,完美组合. 入门培训视频,内含Jira, Confluence, BigGantt, Zephyr, Tempo, Question, ScriptR ...
- Redis 5.0.5集群搭建
Redis 5.0.5集群搭建 一.概述 Redis3.0版本之后支持Cluster. 1.1.redis cluster的现状 目前redis支持的cluster特性: 1):节点自动发现 2):s ...
- Coablt strike官方教程中文版
安装和设置 系统要求 Cobalt Strike的最低系统要求 2 GHz +以上的cpu 2 GB RAM 500MB +可用空间 在Amazon的EC2上,至少使用较高核数的CPU(c1.medi ...