Mybatis基础(增删改查)
项目结构
建表语句
DROP TABLE IF EXISTS `t_role`;
CREATE TABLE `t_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`role_name` varchar(255) DEFAULT NULL,
`note` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
log4j配置文件(log4j.properties)
log4j.rootLogger=DEBUG,stdout
log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n
mybatis配置文件(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>
<!--别名 -->
<typeAliases>
<typeAlias alias="role" type="com.hlbdx.mybatis.model.Role" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!-- type="POOLED" 代表采用Mybatis内部提供的连接池方式 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/ssm" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/hlbdx/mybatis/dao/RoleMapper.xml" />
</mappers>
</configuration>
Java 对象(Role.java)
package com.hlbdx.mybatis.model;
public class Role {
private Long id;
private String roleName;
private String note;
public Long getId() {
return id;
}
public String getRoleName() {
return roleName;
}
public String getNote() {
return note;
}
public void setId(Long id) {
this.id = id;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public void setNote(String note) {
this.note = note;
}
}
mapper接口(RoleMapper.java)
package com.hlbdx.mybatis.dao;
import java.util.List;
import com.hlbdx.mybatis.model.Role;
public interface RoleMapper {
public int insertRole(Role role);
public int deleteRole(Long id);
public int updateRole(Role role);
public Role getRole(Long id);
public List<Role> findRoles(String rolename);
}
mapper映射文件(RoleMapper.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.hlbdx.mybatis.dao.RoleMapper">
<insert id="insertRole">
insert into t_role(role_name,note)
values(#{roleName},#{note});
</insert>
<delete id="deleteRole" parameterType="long">
delete from t_role where
id = #{id}
</delete>
<update id="updateRole" parameterType="role">
update t_role set
role_name = #{roleName},note=#{note} where
id = #{id}
</update>
<select id="getRole" parameterType="long" resultType="role">
select
id,role_name as roleName,note from t_role where id = #{id}
</select>
<select id="findRoles" parameterType="string" resultType="role">
select
id,role_name as roleName,note from t_role where
role_name like
concat('%',#{roleName},'%');
</select>
</mapper>
sqlSessionFactory工具类(SqlSessionFactoryUtils.java)
package com.hlbdx.mybatis.util;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class SqlSessionFactoryUtils {
private final static Class<SqlSessionFactoryUtils> LOCK = SqlSessionFactoryUtils.class;
private static SqlSessionFactory sqlSessionFactory = null;
private SqlSessionFactoryUtils() {
}
// 获取SessionFactory
public static SqlSessionFactory getSqlSessionFactory() {
synchronized (LOCK) {
if (sqlSessionFactory != null) {
return sqlSessionFactory;
}
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return sqlSessionFactory;
}
}
// 获取sqlSession
public static SqlSession openSqlSession() {
if (sqlSessionFactory == null) {
getSqlSessionFactory();
}
return sqlSessionFactory.openSession();
}
}
测试类(TestMybatisDemo.java)
package com.hlbdx.mybatis.test;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import com.hlbdx.mybatis.dao.RoleMapper;
import com.hlbdx.mybatis.model.Role;
import com.hlbdx.mybatis.util.SqlSessionFactoryUtils;
public class TestMybatisDemo {
public static void main(String[] args) {
Logger log = Logger.getLogger(TestMybatisDemo.class);
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionFactoryUtils.openSqlSession();
RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
Role roleSave = new Role();
roleSave.setRoleName("张三");
roleSave.setNote("啦啦啦");
roleMapper.insertRole(roleSave);
log.info("插入" + roleSave.getRoleName() + "成功!");
Role role = roleMapper.getRole(1L);
log.info("获取" + role.getRoleName() + "成功!");
role.setRoleName("李四");
roleMapper.updateRole(role);
log.info("更新" + role.getRoleName() + "成功!");
roleMapper.deleteRole(role.getId());
log.info("删除" + role.getRoleName() + "成功!");
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
}
运行结果