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 ...
随机推荐
- 什么是Singleton?
Singleton:在Java中即指单例设计模式,它是软件开发中最常用的设计模式之一. 单:指唯一 例:指实例 单例设计模式,即某个类在整个系统中只能有一个实例对象可被获取和使用的代码模式. 要点: ...
- jq css3实现跑马灯+大转盘
前端效果, <!DOCTYPE HTML><html><head> <meta http-equiv="Content-Type" con ...
- 【POJ - 3616】Milking Time(动态规划)
Milking Time 直接翻译了 Descriptions 贝茜是一个勤劳的牛.事实上,她如此专注于最大化她的生产力,于是她决定安排下一个N(1≤N≤1,000,000)小时(方便地标记为0. ...
- lumen 路由访问路径
项目目录/public/index.php/接你设置的路由 比如设置了 $app->get('/test', function () use ($app) { return $app-&g ...
- 源码分析--dubbo服务端暴露
服务暴露的入口方法是 ServiceBean 的 onApplicationEvent.onApplicationEvent 是一个事件响应方法,该方法会在收到 Spring 上下文刷新事件后执行服务 ...
- 一.安全NA之syslog SNMP SSH NTP
一.常用命令 配置模式下: no logging console #关闭屏幕实时显示日志,不影响到日志buffer里(show logging) logging console #打开屏幕实时日志显示 ...
- spark任务调度模式,动态资源分配
官网链接: http://spark.apache.org/docs/latest/job-scheduling.html 主要介绍: 1 application级调度方式 2 单个applicati ...
- 用python解析JSON
先来认识下JSON JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于ECMAScript的一个子集. JSON采用完全独立于语言的文本格式,但是也使 ...
- 图解Java数据结构之队列
本篇文章,将对队列进行一个深入的解析. 使用场景 队列在日常生活中十分常见,例如:银行排队办理业务.食堂排队打饭等等,这些都是队列的应用.那么队列有什么特点呢? 我们知道排队的原则就是先来后到,排在前 ...
- 80后,天才程序员, Facebook 第一任 CTO,看看开挂的人生到底有多变态?
鸡仔说:今天介绍一位天才程序员--亚当·德安格洛(Adam D'Angelo),他被<财富>杂志誉为"科技界最聪明的人之一",大学去了被誉为"天才" ...