mybatis的第一个程序

Bertha 。 2022-06-08 03:11 430阅读 0赞

程序结构图:

Center

表结构;

Center 1

创表sql:

CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(200) DEFAULT NULL,
`password` varchar(32) DEFAULT NULL,
`sex` char(1) DEFAULT NULL,
`birthday` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8

User.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">









SqlMapConfig.xml

<?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">



















log4j.properties:

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output…
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

代码:

public class TestMybatis {

@Test
public void testFindUserById() throws Exception {
// 加载配置文件
String resource = “SqlMapConfig.xml”;
InputStream inputStream = Resources.getResourceAsStream(resource);
// 通过配置文件获取到sqlSessionFactory
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 通过sessionFactory对象获取到sqlSession对象
SqlSession sqlSession = sessionFactory.openSession();
// 向数据库发起查询(查询单条记录),并接收返回结果
User user = sqlSession.selectOne(“test.findUserById”, 3);
// 打印结果
System.out.println(user);

// 向数据库发起查询(查询多条记录),并接收返回结果
List list = sqlSession.selectList(“test.findUserList”, “小”);
System.out.println(list.size());
for (User user2 : list) {
System.out.println(user2);
}
}
}

执行结果:

Center 2

发表评论

表情:
评论列表 (有 0 条评论,430人围观)

还没有评论,来说两句吧...

相关阅读