什么是Mybtis?
官方自己介绍说:“MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。”
为了方便,我使用了maven构建项目。
Mybatis环境搭建及简单实例:
1、环境搭建
将下面dependency代码置于pom.xml中
org.mybatis
mybatis
x.x.x
2、配置log4j和Mybatis
在classpath建立一个log4j的配置文件log4j.properties,再建立一个用于配置Mybatis的配置文件mybatis-config.xml文件。mybatis-config配置如下
xml version
="1.0"
encoding
="UTF-8"
?>
configuration
PUBLIC
"-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd"
>
resource
="dbconfig.properties"
>
name
="logImpl"
value
="LOG4J"
/>
type
="hzq.mybatis.source.demo1.entity.User"
alias
="User"
/>
type
="hzq.mybatis.source.demo1.dao.IUserDao"
alias
="UserMapper"
/>
default
="development"
>
id
="development"
>
type
="JDBC"
/>
type
="POOLED"
>
name
="driver"
value
="${driver}"
/>
name
="url"
value
="${url}"
/>
name
="username"
value
="${username}"
/>
name
="password"
value
="${password}"
/>
resource
="hzq/mybatis/source/demo1/UserMapper.xml"
/>
3、简单实例:
①、首先,在mysql数据库mybatis中创建一张sys_users表;
CREATE TABLE `sys_users` (
`userno`
int (
11 )
NOT NULL AUTO_INCREMENT COMMENT
'用户序号'
,
`loginname`
varchar (
64 )
DEFAULT NULL COMMENT
'登陆名'
,
`passwd`
varchar (
64 )
DEFAULT NULL COMMENT
'密码'
,
`username`
varchar (
64 )
DEFAULT NULL COMMENT
'姓名'
,
`job`
varchar (
64 )
DEFAULT NULL COMMENT
'职务'
,
`phone`
varchar (
32 )
DEFAULT NULL COMMENT
'电话'
,
`createtime`
datetime DEFAULT NULL COMMENT
'创建时间'
,
`lastlgntime`
datetime DEFAULT NULL
,
PRIMARY KEY (
`userno` )
)
ENGINE =InnoDB
AUTO_INCREMENT =
0
DEFAULT CHARSET =utf8
ROW_FORMAT =
COMPACT
;
②、包目录结构如下:
③编写一个User实体类
public class User {
private String
userno
;
private String
loginname
;
private String
passwd
;
private String
username
;
private String
job
;
private String
phone
;
private String
createtime
;
private String
lastlgntime
;
public String
getUserno () {
return
userno
;
}
public void
setUserno (String userno) {
this .
userno = userno
;
}
public String
getLoginname () {
return
loginname
;
}
public void
setLoginname (String loginname) {
this .
loginname = loginname
;
}
public String
getPasswd () {
return
passwd
;
}
public void
setPasswd (String passwd) {
this .
passwd = passwd
;
}
public String
getUsername () {
return
username
;
}
public void
setUsername (String username) {
this .
username = username
;
}
public String
getJob () {
return
job
;
}
public void
setJob (String job) {
this .
job = job
;
}
public String
getPhone () {
return
phone
;
}
public void
setPhone (String phone) {
this .
phone = phone
;
}
public String
getCreatetime () {
return
createtime
;
}
public void
setCreatetime (String createtime) {
this .
createtime = createtime
;
}
public String
getLastlgntime () {
return
lastlgntime
;
}
public void
setLastlgntime (String lastlgntime) {
this .
lastlgntime = lastlgntime
;
}
}
④编写IUserDao接口类:
public interface IUserDao {
/**
* 新增
*/
public void
insert (User user)
;
/**
* 获取所有的数据
*
@return
*/
public List
list ()
;
/**
* 根据id更新
*
@param
user
*/
public void
update (User user)
; }
⑤编写UserDaoImpl实现类
public class UserDaoImpl
implements IUserDao {
@Override
public void
insert (User user) {
SqlSession session =
this .getSqlSessionFactory().openSession()
;
session.insert(
"UserMapper.insert"
, user)
;
session.commit()
;
session.close()
;
}
@Override
public List
list () {
SqlSession session =
this .getSqlSessionFactory().openSession()
;
List users = session.selectList(
"UserMapper.list" )
;
session.close()
;
return users
;
}
@Override
public void
update (User user) {
SqlSession session =
this .getSqlSessionFactory().openSession()
;
session.update(
"UserMapper.update"
, user)
;
session.commit()
;
session.close()
;
}
/**
* 获取 SqlSessionFactory
* Mybatis 通过SqlSessionFactory获取SqlSession, 然后才能通过SqlSession与数据库进行交互
*
@return
*/
private SqlSessionFactory
getSqlSessionFactory (){
String resource =
"mybatis-config.xml"
;
SqlSessionFactory sqlSessionFactory =
null;
InputStream stream =
null;
try {
stream = Resources.
getResourceAsStream (resource)
;
sqlSessionFactory =
new SqlSessionFactoryBuilder().build(stream)
;
}
catch (Exception e){
e.printStackTrace()
;
}
return sqlSessionFactory
;
}
}
⑥编写UserMapper文件
xml version
="1.0"
encoding
="UTF-8"
?>
mapper
PUBLIC
"-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"
>
namespace
="UserMapper"
>
id
="tableName"
>
sys_users
id
="field"
>
userno,
loginname,
passwd,
username,
job,
phone,
createtime,
lastlgntime
id
="fieldValue"
>
#{userno},
#{loginname},
#{passwd},
#{username},
#{job},
#{phone},
#{createtime},
#{lastlgntime}
id
="insert"
parameterType
="User"
>
INSERT INTO
refid
="tableName"
>
(
refid
="field"
>
)VALUES (
refid
="fieldValue"
>
)
id
="list"
resultType
="User"
>
SELECT
refid
="field"
>
FROM
refid
="tableName"
>
id
="update"
parameterType
="User"
>
UPDATE
refid
="tableName"
/>
SET
job = #{job}
WHERE
userno = #{userno}
⑦编写测试类
public class UserTest {
private IUserDao
userDao =
new UserDaoImpl()
;
/**
* 新增数据
*/
@Test
public void
save (){
User user =
new User()
;
user.setLoginname(
"admin" )
;
user.setPhone(
"110" )
;
user.setPasswd(
"admin" )
;
user.setJob(
"码农" )
;
DateFormat df =
new SimpleDateFormat(
"yy-MM-dd HH:mm:ss" )
;
user.setCreatetime(df.format(
new Date()))
;
user.setLastlgntime(df.format(
new Date()))
;
userDao .insert(user)
;
}
/**
* 根据id更新
*/
@Test
public void
update (){
User user =
new User()
;
user.setUserno(
2 +
"" )
;
user.setJob(
"Java工程师" )
;
userDao .update(user)
;
}
/**
* 查询所有的数据
*/
@Test
public void
list (){
List users =
userDao .list()
;
for (User u: users
) {
System.
out .println(u.getJob())
;
}
}
}
4、demo源码下载链接:
https://code.csdn.net/mmd0308/mybatis-source/tree/master
https://code.csdn.net/mmd0308/mybatis-source.git
通过这个简单的demo,初步了解Mybatis 的运行机制。接下来进行深一步的了解和学习Mybatis。