博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Mybatis注解方法操作数据库
阅读量:5825 次
发布时间:2019-06-18

本文共 6048 字,大约阅读时间需要 20 分钟。

  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" "">
<
configuration
>
    
<
environments
default
=
"development"
>
        
<
environment
id
=
"development"
>
            
<
transactionManager
type
=
"JDBC"
/>
            
<!-- 配置数据库连接信息 -->
            
<
dataSource
type
=
"POOLED"
>
                
<
property
name
=
"driver"
value
=
"com.mysql.jdbc.Driver"
/>
                
<
property
name
=
"url"
value
=
"jdbc:mysql://127.0.0.1/test"
/>
                
<
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
>

转载地址:http://iqidx.baihongyu.com/

你可能感兴趣的文章
ASP.NET中 HTML标签总结及使用
查看>>
Linux下日志系统的设计
查看>>
爬虫IP被禁的简单解决方法——切换UserAgent
查看>>
php生成word,并下载
查看>>
紫书 习题8-11 UVa 1615 (区间选点问题)
查看>>
asp.net mvc学习(Vs技巧与Httpcontext)
查看>>
float数据在内存中是怎么存储的
查看>>
dedecms 修改标题长度可以修改数据库
查看>>
Matplotlib学习---用matplotlib画直方图/密度图(histogram, density plot)
查看>>
MySQL案列之主从复制出错问题以及pt-slave-restart工具的使用
查看>>
linux 查看剩余内存数
查看>>
测试人员容易遗漏的隐藏缺陷
查看>>
maven+SpringMVC搭建RESTful后端服务框架
查看>>
[BalkanOI2016]Cruise
查看>>
一本书的摘录
查看>>
重排序(转载)
查看>>
python+selenium之字符串切割操作
查看>>
串结构练习——字符串匹配
查看>>
linux下输入密码不回显
查看>>
《构建之法》读书笔记
查看>>