标签:sel factor pack 映射 user 事务 man 添加 new
<?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">
<!-- mybatis的主配置文件 -->
<configuration>
<!-- 加载类路径下的属性文件 -->
<properties resource="db.properties"/>
<!-- 配置环境 -->
<environments default="mysql">
<!-- 配置mysql的环境 -->
<environment id="mysql">
<!-- 配置事务类型 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置数据源(连接池) -->
<dataSource type="POOLED">
<!-- 配置连接数据库的4个基本信息 -->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
</configuration>
public interface UserDao {
/**
* 查询所有
* @return
*/
List<User> findAll();
/**
* 添加用户
*/
void saveUser(User user);
}
<?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="blog.mybatis.dao.UserDao">
<!-- 查询所有 -->
<select id="findAll" resultType="blog.mybatis.domain.User">
select * from user
</select>
<!-- 添加用户 -->
<insert id="saveUser" parameterType="blog.mybatis.domain.User">
insert into user(username,password)values(#{username},#{password})
</insert>
</mapper>
<mappers>
<mapper resource="blog/mybatis/dao/UserDao.xml"/>
<!-- package标签是用于指定dao接口所在的包,当指定完之后就不需要再写mapper、resource或class了
<package name="blog.mybatis.dao"/>
-->
</mappers>
public class UserTest {
public static void main(String[] args) throws Exception{
//1.读取配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//3.使用工厂生产SqlSession对象
SqlSession session = factory.openSession();
//4.使用SqlSession创建接口的代理对象
UserDao userDao = session.getMapper(UserDao.class);
//5.使用代理对象执行方法
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println(user);
}
//6.释放资源
session.close();
in.close();
}
}
public class UserTest {
public static void main(String[] args) throws Exception{
//1.读取配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//3.使用工厂生产SqlSession对象
SqlSession session = factory.openSession();
//4.使用SqlSession创建接口的代理对象
UserDao userDao = session.getMapper(UserDao.class);
//5.使用代理对象执行方法
User user = new User();
user.setUsername("Ming");
user.setPassword("123");
userDao.saveUser(user);
//提交事务
session.commit();
//6.释放资源
session.close();
in.close();
}
}
标签:sel factor pack 映射 user 事务 man 添加 new
原文地址:https://www.cnblogs.com/Elaina/p/13379337.html