以上是目录结构
User实体类
package com.mybatis.yhw.po;
public class User {
private int id;
private String username;
private String password;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
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 + ", username=" + username + ", password="
+ password + ", age=" + age + "]";
}
}
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.mybatis.yhw.po.UserMapper">
<insert id="save" parameterType="com.mybatis.yhw.po.User">
insert into user(username,password,age) values(#{username},#{password},#{age})
</insert>
</mapper>
TestUser.java
package com.mybatis.yhw.test;
import java.io.IOException;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import com.mybatis.yhw.po.User;
public class TestUser {
private User user;
@Test
public void testSave() throws IOException {
user = new User();
user.setUsername("张三");
user.setPassword("123345");
user.setAge(12);
SqlSessionFactory sf = new SqlSessionFactoryBuilder().
build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession session = sf.openSession();
session.insert("com.mybatis.yhw.po.UserMapper.save", user);
session.commit();
session.close();
System.out.println(user.toString());
}
}
mybatis-config.xml
对mybatis.config.xml的理解:
第一: type = "JDBC",type="POOLED" 都是别名;
<?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">
<!--
事务管理器
JDBC事务管理器,
表示一个权限定名的别名 org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory
-->
<transactionManager type="JDBC" />
<!--
数据源连接池
POOLED 表示mybatis
内部内置连接池的一个别名 org.apache.ibatis.datasource.pooled.PooledDataSourceFactory
-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/mybatis/yhw/po/UserMapper.xml"/>
</mappers>
</configuration>