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
程序员的眼里,不止有代码和bug,还有诗与远方和妹子!!!