DROP TABLE IF EXISTS `website`; CREATE TABLE `website` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `url` varchar(30) COLLATE utf8_unicode_ci DEFAULT '', `age` tinyint(3) unsigned NOT NULL, `country` char(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `createtime` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;创建 MyBatis 程序的步骤为:下载jar包 -> 部署jar包 -> 编写MyBatis核心配置文件 -> 创建实体类 -> 创建DAO接口 -> 创建SQL映射文件 -> 编写测试类
# Global logging configuration
log4j.rootLogger=ERROR,stdout
# MyBatis logging configuration...
log4j.logger.net.biancheng=DEBUG
# 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
package net.biancheng.po; import java.util.Date; public class Website { private int id; private String name; private String url; private int age; private String country; private Date createtime; /*省略setter和getter方法*/ @Override public String toString() { return "id" + id + "name" + name + "url" + url + "age" + age + "country" + country + "createtime" + createtime; } }
<?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="net.biancheng.mapper.WebsiteMapper"> <!-- 添加一个网站 --> <insert id="addWebsite" parameterType="net.biancheng.po.Website"> insert into website (name,url,age,country) values(#{name},#{url},#{age},#{country}) </insert> <!-- 查询所有网站信息 --> <select id="selectAllWebsite" resultType="net.biancheng.po.Website"> select * from website </select> </mapper>上述代码中,<mapper> 元素是配置文件的根元素,它包含了 namespace 属性,该属性值通常设置为“包名+SQL映射文件名”,用于指定唯一的命名空间。
<?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> <settings> <setting name="logImpl" value="LOG4J" /> </settings> <!-- 配置mybatis运行环境 --> <environments default="development"> <environment id="development"> <!-- 使用JDBC的事务管理 --> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <!-- MySQL数据库驱动 --> <property name="driver" value="com.mysql.jdbc.Driver" /> <!-- 连接数据库的URL --> <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf8" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <!-- 将mapper文件加入到配置文件中 --> <mappers> <mapper resource="net/biancheng/mapper/WebsiteMapper.xml" /> </mappers> </configuration>上述映射文件和配置文件都不需要读者完全手动编写,都可以从 MyBatis 使用手册中复制,然后做简单修改。
package net.biancheng.test; import java.io.IOException; import java.io.InputStream; import java.util.List; 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 net.biancheng.po.Website; public class Test { public static void main(String[] args) throws IOException { // 读取配置文件mybatis-config.xml InputStream config = Resources.getResourceAsStream("mybatis-config.xml"); // 根据配置文件构建SqlSessionFactory SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config); // 通过SqlSessionFactory创建SqlSession SqlSession ss = ssf.openSession(); // SqlSession执行文件中定义的SQL,并返回映射结果 // 添加网站 Website website = new Website(); website.setName("编程帮"); website.setUrl("https://www.lmcjl.com/"); website.setAge(21); website.setCountry("CN"); ss.insert("net.biancheng.mapper.WebsiteMapper.addWebsite", website); // 查询所有网站 List<Website> listWeb = ss.selectList("net.biancheng.mapper.WebsiteMapper.selectAllWebsite"); for (Website site : listWeb) { System.out.println(site); } // 提交事务 ss.commit(); // 关闭 SqlSession ss.close(); } }运行结果如下。
DEBUG [main] - ==> Preparing: insert into website (name,url,age,country) values(?,?,?,?)
DEBUG [main] - ==> Parameters: 编程帮(String), https://www.lmcjl.com/(String), 21(Integer), CN(String)
DEBUG [main] - <== Updates: 1
DEBUG [main] - ==> Preparing: select * from website
DEBUG [main] - ==> Parameters:
DEBUG [main] - <== Total: 1
Website[id=1,name=编程帮,url=https://www.lmcjl.com/,age=21,country=CN,createtime=Tue Feb 23 10:20:40 CST 2021]
本文链接:http://task.lmcjl.com/news/18730.html