ssm框架之mybatis框架搭建
第一步 引入依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- mybatis mysql相关依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
第二步 编写配置文件
最终目录如下:
我们要编写mybatis-config.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">
<configuration>
<settings>
<setting name="logImpl" value="LOG4J" />
</settings>
<typeAliases>
<package name="com.dts.entity" />
</typeAliases>
<!-- 配置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/cdes?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<!-- 将mapper文件加入到配置文件中 -->
<mappers>
<mapper resource="mapper/WebsiteMapper.xml" />
</mappers>
</configuration>
然后编写log4j.properties,内容如下
# Global logging configuration
log4j.rootLogger=ERROR,stdout
# MyBatis logging configuration...
log4j.logger.com.dts=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
第三步 编写实体类 mapper 和sql脚本
package com.dts.entity;
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;
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "id" + id + "name" + name + "url" + url + "age" + age + "country" + country + "createtime" + createtime;
}
}
package com.dts.mapper;
import com.dts.entity.Website;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface WebsiteMapper {
void addWebsite(Website website);
List<Website> selectAllWebsite();
@Select("select * from website where id = #{id}")
Website findById(Integer id);
List<Website> selectByIds(List<Integer> ids);
List<Website> selectByCondition(Website website);
void updateWebsite(Website website);
void deleteWebsite(Integer id);
void deleteWebsiteByIds(List<Integer> ids);
}
<?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.dts.mapper.WebsiteMapper">
<!-- 添加一个网站 -->
<insert id="addWebsite" parameterType="com.dts.entity.Website">
insert into website
(name,url,age,country)
values(#{name},#{url},#{age},#{country})
</insert>
<!-- 查询所有网站信息 -->
<select id="selectAllWebsite"
resultType="com.dts.entity.Website">
select * from website
</select>
<select id="selectByIds" resultType="com.dts.entity.Website">
select * from website where id in
<foreach collection="list" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</select>
<select id="selectByCondition" resultType="com.dts.entity.Website">
select * from website
<where>
<if test="name != null and name != ''">
and name like concat('%',#{name},'%')
</if>
<if test="country != null and country != ''">
and country like concat('%',#{country},'%')
</if>
<if test="age != null and age != ''">
and age = #{age}
</if>
</where>
</select>
<update id="updateWebsite">
update website
<set>
<if test="name != null and name != ''">
name = #{name},
</if>
<if test="url != null and url != ''">
url = #{url},
</if>
<if test="age != null and age != ''">
age = #{age},
</if>
<if test="country != null and country != ''">
country = #{country},
</if>
</set>
where id = #{id}
</update>
<delete id="deleteWebsite">
delete from website where id = #{id}
</delete>
<delete id="deleteWebsiteByIds">
delete from website where id in
<foreach collection="list" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</delete>
</mapper>
最后 编写test方法
package com.dts;
import com.dts.entity.Website;
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 java.io.InputStream;
import java.util.List;
public class MybatisTest {
public static void main(String[] args)throws Exception {
test1();
}
public static void test1() throws Exception {
// 读取配置文件mybatis-config.xml
InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
// 根据配置文件构建SqlSessionFactory
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
// 通过SqlSessionFactory创建SqlSession
SqlSession ss = ssf.openSession();
ss.getConnection().setAutoCommit(false);
// SqlSession执行文件中定义的SQL,并返回映射结果
// 添加网站
Website website = new Website();
website.setName("编程帮");
website.setUrl("https://www.cainiaoplus.com/");
website.setAge(21);
website.setCountry("CN");
ss.insert("com.dts.mapper.WebsiteMapper.addWebsite", website);
//这种方式
// WebsiteMapper mapper = ss.getMapper(WebsiteMapper.class);
// mapper.addWebsite(website);
// 查询所有网站
List<Website> listWeb = ss.selectList("com.dts.mapper.WebsiteMapper.selectAllWebsite");
for (Website site : listWeb) {
System.out.println(site);
}
// 提交事务
ss.commit();
// 关闭 SqlSession
ss.close();
}
}
经过以上步骤,mybatis框架就算搭建完成了。最终项目结构如下