Mybatis注解方法操作数据库
2024-08-27 03:47:39
Java中使用Mybatis操作数据库主要有两种方法:注解和xml配置,注解相对比较简单和方便,两种方式的效果一致。本文以注解的方式说明用Mybatis访问数据库的方法
一、创建数据表(MySql)
1
2
3
4
5
6
7
8
9
|
-- ---------------------------- -- Table structure for admininfo -- ---------------------------- DROP TABLE IF EXISTS `admininfo`; CREATE TABLE `admininfo` ( `ID` int (11) NOT NULL AUTO_INCREMENT, `AdminName` varchar (20) NOT NULL , PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=latin1; |
二、创建mybatis的配置文件:mybatisConf.xml,由于使用maven进行管理,所以放在java-->resources文件夹下,其它位置也可以,只有最终在\target\classes\mybatisConf.xml生成文件即可
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<? 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 > < environments default = "development" > < environment id = "development" > < transactionManager type = "JDBC" /> <!-- 配置数据库连接信息 --> < dataSource type = "POOLED" > < property name = "driver" value = "com.mysql.jdbc.Driver" /> < property name = "username" value = "root" /> < property name = "password" value = "root" /> </ dataSource > </ environment > </ environments > < mappers > <!-- 注册映射接口,该接口文件包含了数据访问方法和SQL --> < mapper class = "dal.dataaccess.IAdminInfoMapper" /> </ mappers > </ configuration > |
三、创建IAdminInfoMapper文件(本文中包名为dal.dataaccess)
该接口的功能主要是提供对AdminInfo表的数据操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
package dal.dataaccess; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import dal.beans.AdminInfo; import dal.beans.AdminRightInfo; public interface IAdminInfoMapper { //使用@Select注解指明getById方法要执行的SQL @Select ( "select * from admininfo where id=#{id}" ) public AdminInfo getById( int id); //使用@Select注解指明getAll方法要执行的SQL @Select ( "select * from admininfo" ) public List<AdminInfo> getAll(); //使用@Insert注解指明add方法要执行的SQL @Insert ( "insert into admininfo(adminName) values(#{adminName})" ) public int add(AdminInfo user); //使用@Update注解指明update方法要执行的SQL @Update ( "update admininfo set adminName=#{adminName} where id=#{id}" ) public int update(AdminInfo user); //使用@Delete注解指明deleteById方法要执行的SQL @Delete ( "delete from admininfo where id=#{id}" ) public int deleteById( int id); } |
四、定义操作数据库的公共方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
package framework.utils; import java.io.InputStream; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtil { /** * 获取SqlSessionFactory * * @return SqlSessionFactory */ public static SqlSessionFactory getSqlSessionFactory() { String resource = "mybatisConf.xml" ; InputStream is = MyBatisUtil. class .getClassLoader().getResourceAsStream(resource); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); return factory; } /** * 获取SqlSession * * @return SqlSession */ public static SqlSession getSqlSession() { return getSqlSessionFactory().openSession(); } /** * 获取SqlSession * * @param isAutoCommit * true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务 false * 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession. * commit()提交事务 * @return SqlSession */ public static SqlSession getSqlSession( boolean isAutoCommit) { return getSqlSessionFactory().openSession(isAutoCommit); } } |
五、对adminInfo表进行增删改查
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
package test; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import dal.beans.*; import framework.utils.MyBatisUtil; import dal.dataaccess.*; public class MybatisAnnotationTest { @Test public void Select() { SqlSession sqlSession = MyBatisUtil.getSqlSession(); // 得到AdminInfoMapper接口的实现类对象,IAdminInfoMapper接口的实现类对象由sqlSession.getMapper(IAdminInfoMapper.class)动态构建出来 IAdminInfoMapper mapper = sqlSession.getMapper(IAdminInfoMapper. class ); // 执行查询操作,将查询结果自动封装成User返回 AdminInfo bean = mapper.getById( 13 ); // 使用SqlSession执行完SQL之后需要关闭SqlSession sqlSession.close(); System.out.println(bean.getId()); System.out.println(bean.getAdminName()); } @Test public void SelectAll() { SqlSession sqlSession = MyBatisUtil.getSqlSession(); IAdminInfoMapper mapper = sqlSession.getMapper(IAdminInfoMapper. class ); List<AdminInfo> bean = mapper.getAll(); sqlSession.close(); System.out.println(bean.size()); } @Test public void Insert() { SqlSession sqlSession = MyBatisUtil.getSqlSession(); IAdminInfoMapper mapper = sqlSession.getMapper(IAdminInfoMapper. class ); AdminInfo bean = new AdminInfo(); bean.setAdminName( "Admin" + System.currentTimeMillis()); int result = mapper.add(bean); sqlSession.commit(); sqlSession.close(); System.out.println(result); } @Test public void Update() { SqlSession sqlSession = MyBatisUtil.getSqlSession(); IAdminInfoMapper mapper = sqlSession.getMapper(IAdminInfoMapper. class ); AdminInfo bean = new AdminInfo(); bean.setId( 12 ); bean.setAdminName( "Admin" + System.currentTimeMillis()); int result = mapper.update(bean); sqlSession.commit(); sqlSession.close(); System.out.println(result); } @Test public void Delete() { SqlSession sqlSession = MyBatisUtil.getSqlSession(); IAdminInfoMapper mapper = sqlSession.getMapper(IAdminInfoMapper. class ); int result = mapper.deleteById( 12 ); sqlSession.commit(); sqlSession.close(); System.out.println(result); } } |
六、由于使用了maven进行依赖管理,pom.xml还需要添加
1
2
3
4
5
6
7
8
9
10
|
< dependency > < groupId >mysql</ groupId > < artifactId >mysql-connector-java</ artifactId > < version >5.1.38</ version > </ dependency > < dependency > < groupId >org.mybatis</ groupId > < artifactId >mybatis</ artifactId > < version >3.3.0</ version > </ dependency > |
最新文章
- 如何区分Babel中的stage-0,stage-1,stage-2以及stage-3(二)
- html+css学习笔记:实用LessColor函数搭建配色方案
- [Java Web整合开发王者归来&#183;刘京华] 2、 Java Web开发概述
- myeclipse自动import
- 如何实现SSH断开后 进程仍然在后台运行
- gdb使用_转
- Spring中使用Hibernate
- z-index兼容问题:关于ie6/7下的z-index
- King&#39;s Quest - poj 1904(强连通分量+外挂输入输出)
- sping注解原理
- MySQL数据库的数据备份和恢复(导入和导出)命令操作语法【转】
- PAT-L3-球队“食物链”-dfs-状压-set
- java并发请求多个接口,顺序返回
- 群发技术-使用python3给微信好友群发消息
- shiro登录验证原理
- read()、write()返回 Input/output error, Device or resource busy解决
- 算法入门:最大子序列和的四种算法(Java)
- Java知多少(55)线程
- 逆袭之旅DAY.XIA.Object中常用方法
- 【2018年12月10日】A股最便宜的股票
热门文章
- supervisor error: <;class &#39;socket.error&#39;>;, [Errno 110]
- 亚马逊EC2根硬盘空间扩容
- c语言中数组,指针数组,数组指针,二维数组指针
- linux命令(22):mkdir命令
- 小知识-为什么Linux不需要磁盘碎片整理
- window.screen.height和window.screen.availHeight和document.body.clientHeight和document.documentElement.clientHeight
- 一个有趣的基于Django的调试插件--django-debug-toolbar
- redis之(八)redis的有序集合类型的命令
- SEO如何写好文章标题
- APP线上问题收集信息整理