1需要用到的包:
mybatis-3.1.1.jar log4j-1.2.15.jar
当然还有 mysql 的驱动包
2建立数据表:
CREATE TABLE `user` ( `userId` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(50) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, `comment` varchar(1000) DEFAULT NULL, PRIMARY KEY (`userId`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8
3规划好你项目的结构
com.seatno.log4j 为我的 日志测试类
4:数据实体User
package com.seatno.entity; public class User { private String userId; private String userName; private String password; private String comment; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } 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 String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } }
5:写DAO层接口
package com.seatno.dao; imp
ort java.util.List; imp ort org.apache.ibatis.annotations.Param; imp ort org.apache.ibatis.annotations.Select; imp ort com.seatno.entity.User; public interface UserDao { public int insert(User user); public int update(User user); public int delete(String userName); public List<User> selectAll(); public int countAll(); public User findByUserName(String userName); //通过注释方式 绑定SQL 语句 @Select("SELECT * FROM user WHERE userId = #{userId}") User getUser(@Param("userId") String userId); }
6写mybatis配置文件
文件名任意:我这里取名为MyBatis-Configuration.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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/study?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <mappers> <mapper resource="UserDaoMapper.xml"/><!-- 若不直接在src下,需要加入路径,默认根是classpath --> </mappers> </configuration>
7写SQL映射文件
如果采用注释方式就不需要了,我很喜欢采用注释方式;<?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.seatno.dao.UserDao"> <select id="countAll" resultType="int"> select count(*) c from user; </select> <select id="selectAll" resultType="com.seatno.entity.User"> select * from user order by userName asc </select> <insert id="insert" parameterType="com.seatno.entity.User"> insert into user(userName,password,comment) values(#{userName},#{password},#{comment}) </insert> <update id="update" parameterType="com.seatno.entity.User"> update user set userName=#{userName},password=#{password},comment=#{comment} where userName=#{userName} </update> <delete id="delete" parameterType="int"> delete from user where userName=#{userName} </delete> <select id="findByUserName" parameterType="String" resultType="com.seatno.entity.User"> select * from user where userName=#{userName} </select> </mapper>
8写个测试类试试 UserDaoTest.java
package com.seatno.dao.impl; imp
ort java.io.Reader; imp ort java.util.Iterator; imp ort java.util.List; imp ort org.apache.ibatis.io.Resources; imp ort org.apache.ibatis.session.SqlSession; imp ort org.apache.ibatis.session.SqlSessionFactory; imp ort org.apache.ibatis.session.SqlSessionFactoryBuilder; imp ort org.apache.log4j.Logger; imp ort org.junit.Test;//添加测试框架类 imp ort com.seatno.dao.UserDao; imp ort com.seatno.entity.User; imp ort com.seatno.log4j.log4jTest; public class UserDaoTest { //添加日志输出,你可以不要, 这个需要配置文件 log4j.properties(放在根目录下面) Logger logger = Logger.getLogger(log4jTest.class); @Test //表示该类是测试用例函数 public void userDaoTest() throws Exception { String resource = "MyBatis-Configuration.xml"; Reader reader = Resources.getResourceAsReader(resource); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(reader); SqlSession session = factory.openSession(); UserDao userDao = session.getMapper(UserDao.class);//这是关键 //插入数据 2条做测试 User user = new User(); user.setUserName("我是建伟"); user.setPassword("123456"); user.setComment("我做电子商务"); userDao.insert(user); user.setUserName("jianwei"); user.setPassword("123456"); user.setComment("备注建伟"); userDao.insert(user); System.out.println("记录条数:"+userDao.countAll()); //通过userId获取一个对象 User tUser=userDao.getUser("2"); System.out.println("getUser:用户名:"+tUser.getUserName()+"密码:"+tUser.getPassword()); List<User> users = userDao.selectAll(); Iterator<User> iter = users.iterator(); while(iter.hasNext()){ User u = iter.next(); System.out.println("用户名:"+u.getUserName()+"密码:"+u.getPassword()); } //更新数据 user.setComment("I love you"); userDao.update(user); User u = userDao.findByUserName("jianwei"); System.out.println(u.getComment());
//通过名称删除数据 userDao.delete("jianwei"); System.out.println("记录条数:"+userDao.countAll()); // 提交数据 session.commit(); session.close(); } }
9, log4j.properties文件
log4j.类库默认使用根(classpath)下的这个文件,如果需要另配文件名需要手动加载这个文件,请参考我的其他文档;A1,A2,A3 表示定义3个不同的日志输出方式
log4j.rootCategory=INFO,A1,A2,A3
log4j.appender.A1=org.apache.log4j.ConsoleAppender //控制台输出
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%4p [%t] (%F:%L) - %m%n
log4j.appender.A2=org.apache.log4j.RollingFileAppender
log4j.appender.A2.File=./javalog.log //文件输出 ,表示在项目的根下建立日志文件
log4j.appender.A2.MaxFileSize = 1KB
log4j.appender.A2.MaxBackupIndex = 3 //备份3个文件
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=%d{yyyy-MM-dd hh:mm:ss}:%p %t %c - %m%n
log4j.appender.A3=org.apache.log4j.jdbc.JDBCAppender // 保存到数据库
log4j.appender.A3.URL=jdbc:mysql://localhost:3306/study
log4j.appender.A3.driver=com.mysql.jdbc.Driver
log4j.appender.A3.user=root
log4j.appender.A3.password=123456
log4j.appender.A3.layout=org.apache.log4j.PatternLayout
log4j.appender.A3.layout.ConversionPattern=INSERT INTO log4j(createDate,thread,level,class,message) values(\'%d\',\'%t\',\'%-5p\',\'%c\',\'%m\')//一下为mybatisSQL 输出
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG