项目截图
项目建立步骤:
1、在src目录下建立dp.properties文件,存放配置信息(需要自己在Oracle数据库建表)
jjdbc.driver=oracle.jdbc.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username=bjsxt
jdbc.password=123
2、建立MyBatisUtil工具类
package cn.bjsxt.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 MyBatisUtil {
private static SqlSessionFactory factory=null;
static {
try {
InputStream is = Resources.getResourceAsStream("mybatis-cfg.xml");
factory=new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSession() {
SqlSession session=null;
if (factory!=null) {
//true表示开启自动提交功能,防止回滚,但是运行多条sql语句可能出问题
//session=factory.openSession(true);
session=factory.openSession();
}
return session;
}
}
3、log4j.properties 文件,设置日志输出格式
# Set root category priority to INFO and its only appender to CONSOLE.
log4j.rootCategory=ERROR, CONSOLE
# log4j.rootCategory=DEBUG, CONSOLE, LOGFILE
# 单独设置sql语句的输出级别为DEBUG级别
#方法级别
#log4j.logger.cn.bjsxt.mapper.UserMapper.selAll=DEBUG
#类级别
# log4j.logger.cn.bjsxt.mapper.UserMapper=DEBUG
# 包级别
log4j.logger.cn.bjsxt.mapper=DEBUG
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=- %m%n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:/test.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=- %m %l%n
4、mybatie-cfg.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>
<!--properties 加载外部文件 -->
<properties resource="db.properties"></properties>
<!-- 用于指定使用哪个环境 mysql故障 故采用oracle default:用于指定使用的环境id -->
<settings>
<!-- 设置mybatis使用log4j支持 -->
<setting name="logImpl" value="LOG4J" />
</settings>
<typeAliases>
<!-- typeAlias 给类起别名,在UserMapper使用时直接引用类名即可 -->
<!-- <typeAlias type="cn.bjsxt.pojo.User"/> -->
<package name="cn.bjsxt.pojo" />
</typeAliases>
<environments default="dev">
<!-- 用于配置开发环境 id:环境的唯一识别码 -->
<environment id="dev">
<!-- 事务管理器 type:用于设置mybaties采用什么方式管理事务 JDBC表示采用和JDBC一样的事务管理方式 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 数据源/连接池,用于配置连接池和数据库连接的参数 type:用于设置mybatis是否采用连接池技术 POOLED表示mybatis采用连接池技术 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<!-- 扫描mapper文件 -->
<mappers>
<mapper resource="cn/bjsxt/mapper/UserMapper.xml" />
</mappers>
</configuration>
5、UserMapper.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">
<!--
namespace:命名空间,可以随意定义,一般情况下要写全限定路径
MyBatis管理SQL语句是通过namespace+id来定位的
-->
<mapper namespace="cn.bjsxt.mapper.UserMapper">
<!-- 新增 -->
<insert id="insUser" parameterType="user">
insert into t_user values(#{id},#{username},#{password})
</insert>
<!-- 修改 -->
<update id="updUser" parameterType="user">
update t_user set username=#{username},password=#{password} where id=#{id}
</update>
<update id="delUser" parameterType="user">
delete from t_user where id=#{id}
</update>
</mapper>
6、实体类
package cn.bjsxt.pojo;
import java.io.Serializable;
public class User implements Serializable {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(int id, String username, String password) {
super();
this.id = id;
this.username = username;
this.password = password;
}
public User() {
super();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((password == null) ? 0 : password.hashCode());
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id != other.id)
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
}
}
7、主类
package cn.bjsxt.test;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import cn.bjsxt.pojo.User;
import cn.bjsxt.util.MyBatisUtil;
public class TestInsert {
@Test
public void TestDel() {
SqlSession session = MyBatisUtil.getSession();
User user = new User();
user.setId(8);
int num = session.delete("cn.bjsxt.mapper.UserMapper.delUser", user);
if (num>0) {
System.out.println("删除成功");
session.commit();
} else {
System.out.println("删除失败");
session.rollback();
}
}
@Test
public void testUpd() {
SqlSession session = MyBatisUtil.getSession();
User user = new User();
user.setId(8);
user.setUsername("普京");
user.setPassword("666");
int num = session.update("cn.bjsxt.mapper.UserMapper.updUser", user);
if (num>0) {
System.out.println("更新成功");
session.commit();
}else {
System.out.println("更新失败");
session.rollback();
}
session.close();
}
//使用junit时,每次要运行一个方法都要在方法前面加@Test,否则会报无法解析的异常
@Test
public void testIns() {
SqlSession session = MyBatisUtil.getSession();
User user = new User();
user.setId(8);
user.setUsername("小京");
user.setPassword("123");
int num = session.insert("cn.bjsxt.mapper.UserMapper.insUser", user);
if (num>0) {
//成功时,提交事务,防止回滚
System.out.println("新增成功");
session.commit();
}else {
//失败时,回滚事务
System.out.println("新增失败");
session.rollback();
}
//关闭资源
session.close();
}
}
8、运行结果演示(因为该数据已经插入,所以插入失败)