参考:http://www.cnblogs.com/hellokitty1/p/5216025.html
先附上项目的结构
mybatis需要jar包:mybatis-3.3.0.jar
sqlserver驱动jar包:sqljdbc4.jar
日志记录jar包:log4j.jar、log4j-core-2.2.jar
最好放在src文件下
sqlserver.properties
jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://localhost:1433;useUnicode=true;databaseName=mybatis
jdbc.username=sa
jdbc.password=12345678
通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件、甚至是套接口服务
log4j的两种配置xml与properties
(1)log4j.properties
### 设置Logger输出级别和输出目的地 ###
log4j.rootLogger=debug,stdout,logfile
### 把日志信息输出到控制台 ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
### 把日志信息输出到文件:jbit.log ###
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=jbit.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n
###显示SQL语句部分
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
(2)log4j2.xml
<Configuration status="OFF">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
Console>
Appenders>
<Loggers>
<Logger name="hive.server2.query.ApiQueryTest" level="trace">
<AppenderRef ref="Console" />
Logger>
<Logger name="hive.server2.query" level="debug">
<AppenderRef ref="Console" />
Logger>
<Root level="error">
<AppenderRef ref="Console" />
Root>
Loggers>
Configuration>
<configuration>
<properties resource="sqlserver.properties">properties>
<environments default="mybatis">
<environment id="mybatis">
<transactionManager type="JDBC">transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}">property>
<property name="url" value="${jdbc.url}">property>
<property name="username" value="${jdbc.username}">property>
<property name="password" value="${jdbc.password}">property>
dataSource>
environment>
environments>
configuration>
public class UserBean {
private static final long serialVersionUID=1L;
private Integer id;
private String username;
private String password;
private Double account;
public UserBean() {
super();
}
public UserBean(Integer id, String username, String password, Double account) {
super();
this.id = id;
this.username = username;
this.password = password;
this.account = account;
}
public UserBean( String username, String password, Double account) {
super();
this.username = username;
this.password = password;
this.account = account;
}
public Integer getId() {
return id;
}
public void setId(Integer 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 Double getAccount() {
return account;
}
public void setAccount(Double account) {
this.account = account;
}
@Override
public String toString() {
return "UserBean{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", account=" + account +
'}';
}
}
(1)UserMapper.java
public interface UserMapper {
/**
* 新增用戶
* @param user
* @return
* @throws Exception
*/
public int insertUser(UserBean user) throws Exception;
/**
* 修改用戶
* @param user
* @param id
* @return
* @throws Exception
*/
public int updateUser (UserBean user,int id) throws Exception;
/**
* 刪除用戶
* @param id
* @return
* @throws Exception
*/
public int deleteUser(int id) throws Exception;
/**
* 根据id查询用户信息
* @param id
* @return
* @throws Exception
*/
public UserBean selectUserById(int id) throws Exception;
/**
* 查询所有的用户信息
* @return
* @throws Exception
*/
public List selectAllUser() throws Exception;
}
<mapper namespace="com.mybatis.mapper.UserMapper">
<resultMap id="userMap" type="com.mybatis.beans.UserBean">
<id property="id" column="id" javaType="java.lang.Integer">id>
<result property="username" column="username" javaType="java.lang.String">result>
<result property="password" column="password" javaType="java.lang.String">result>
<result property="account" column="account" javaType="java.lang.Double">result>
resultMap>
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
insert into mybatis_t_user (id,username,password,account) values (#{id},#{username},#{password},#{account})
insert>
<update id="updateUser" >
update mybatis_t_user set username=#{username},password=#{password},account=#{account} where id=#{id}
update>
<delete id="deleteUser" parameterType="int">
delete from mybatis_t_user where id=#{id}
delete>
<select id="selectUserById" parameterType="int" resultMap="userMap">
select * from mybatis_t_user where id=#{id}
select>
<select id="selectAllUser" resultMap="userMap">
select * from mybatis_t_user
select>
mapper>
这时需要为mybatis.cfg.xml里注册UserMapper.xml文件。
<configuration>
<properties resource="sqlserver.properties">properties>
<environments default="mybatis">
<environment id="mybatis">
<transactionManager type="JDBC">transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}">property>
<property name="url" value="${jdbc.url}">property>
<property name="username" value="${jdbc.username}">property>
<property name="password" value="${jdbc.password}">property>
dataSource>
environment>
environments>
<mappers>
-->
<mapper resource="com/mybatis/mapper/userMapper.xml" />
mappers>
configuration>
DBTools.java
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 DBTools {
public static SqlSessionFactory sessionFactory;
static{
try {
//使用MyBatis提供的Resources类加载mybatis的配置文件
Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml");
//构建sqlSession的工厂
sessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
//创建能执行映射文件中sql的sqlSession
public static SqlSession getSession(){
return sessionFactory.openSession();
}
}
import java.util.List;
import com.mybatis.beans.UserBean;
import com.mybatis.mapper.UserMapper;
import com.mybatis.tools.DBTools;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
public class UserService {
/**
* 新增用户
*/
@Test
public void insertUser() {
SqlSession session =DBTools.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
UserBean user = new UserBean(123,"张三", "1314520", 7000.0);
try {
mapper.insertUser(user);
System.out.println(user.toString());
session.commit();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
}
/**
* 删除用户
*/
@Test
public void deleteUser(){
SqlSession session= DBTools.getSession();
UserMapper mapper=session.getMapper(UserMapper.class);
try {
mapper.deleteUser(1);
session.commit();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
}
/**
* 根据id查询用户
*/
@Test
public void selectUserById(){
SqlSession session=DBTools.getSession();
UserMapper mapper=session.getMapper(UserMapper.class);
try {
UserBean user= mapper.selectUserById(2);
System.out.println(user.toString());
session.commit();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
}
/**
* 查询所有的用户
*/
@Test
public void selectAllUser(){
SqlSession session=DBTools.getSession();
UserMapper mapper=session.getMapper(UserMapper.class);
try {
List user=mapper.selectAllUser();
System.out.println(user.toString());
session.commit();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
}
}
orm工具的基本思想
无论是用过的hibernate,mybatis,他们有一个共同点:
1. 从配置文件(通常是XML配置文件中)得到 sessionfactory.
2. 由sessionfactory 产生 session
3. 在session 中完成对数据的增删改查和事务提交等.
4. 在用完之后关闭session 。
5. 在java 对象和 数据库之间有做mapping 的配置文件,也通常是xml 文件。