4.0.0
com.gyoomi
Learning-MyBatis
1.0-SNAPSHOT
UTF-8
UTF-8
1.8
ognl
ognl
3.1.16
compile
true
org.javassist
javassist
3.22.0-GA
compile
true
org.slf4j
slf4j-api
1.7.25
true
org.slf4j
slf4j-log4j12
1.7.25
true
log4j
log4j
1.2.17
true
org.apache.logging.log4j
log4j-core
2.3
true
commons-logging
commons-logging
1.2
true
cglib
cglib
3.2.5
true
org.junit.vintage
junit-vintage-engine
4.12.2
test
org.hsqldb
hsqldb
2.3.5
test
org.apache.derby
derby
10.12.1.1
test
org.mockito
mockito-core
2.12.0
test
commons-dbcp
commons-dbcp
1.4
test
org.jboss.spec.javax.transaction
jboss-transaction-api_1.2_spec
1.0.1.Final
test
org.apache.velocity
velocity
1.7
test
org.postgresql
postgresql
42.1.4.jre6
test
org.assertj
assertj-core
1.7.1
test
eu.codearte.catch-exception
catch-exception
1.4.4
test
ru.yandex.qatools.embed
postgresql-embedded
2.5
test
mysql
mysql-connector-java
5.1.6
junit
junit
4.11
test
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`deptment` varchar(255) DEFAULT NULL,
`phone` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`status` int(11) DEFAULT NULL,
`create_date` datetime DEFAULT NULL,
`remark` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4;
public interface UserMapper {
User save(User user);
}
public class UserMapperImpl implements UserMapper {
private static final String NAME_SPACE = "UserMapper.";
private static SqlSessionFactory ssf;
private static Reader reader;
static {
try {
reader = Resources.getResourceAsReader("mybatis-config.xml");
ssf = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public User save(User user) {
SqlSession sqlSession = ssf.openSession();
int rows = sqlSession.insert(NAME_SPACE + "save", user);
sqlSession.commit();
if (rows > 0) {
return user;
} else {
return null;
}
}
}
MyBatis-config.xml:
UserMapper.xml:
SELECT LAST_INSERT_ID();
INSERT INTO t_user
(id, user_name, password, deptment, phone, email, status, create_date, remark)
VALUES
(null, #{userName}, #{password}, #{deptment}, #{phone}, #{email}, #{status}, #{createDate}, #{remark})
创建Main.java(其实这里是不规范的,一般是要写JUnit单元测试的。)
public class Main {
public static void main(String[] args) {
UserMapper userMapper = new UserMapperImpl();
User user = new User();
user.setPassword("123");
user.setCreateDate(new Date());
user.setDeptment("研发部门");
user.setEmail("[email protected]");
user.setStatus(1);
user.setUserName("张三");
user.setPhone("13888888888");
user.setRemark("系统默认用户");
User userToReturn = userMapper.save(user);
System.out.println(userToReturn);
}
}
执行完上述3步后,整体的代码结构如下:
执行Main方法后,打开数据看到t_user表新增了一条记录。
支持MyBatis的源码阅读的环境搭建并测试完毕。下面就让我们开始畅快地阅读源码吧!
Github地址:MyBatis源码