码迷,mamicode.com
首页 > 编程语言 > 详细

java:Mybatis框架1(基本配置,log4j)

时间:2017-08-31 21:09:03      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:update   style   interface   on()   pool   bug   main   override   names   

1.mybatis01:

 

技术分享

 

  db.properties:

 

技术分享

 

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=root

 

  log4j.properties:

技术分享

 

#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.org.apache.ibatis=DEBUG
#log4j.rootLogger=warn,appender1  
#log4j.appender.appender1=org.apache.log4j.ConsoleAppender  
#log4j.appender.appender1.layout=org.apache.log4j.SimpleLayout  

  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>



    <!-- 加载属性文件 -->
       <properties resource="db.properties"/>
    <environments default="development">
         <environment id="development">
             
             <!-- 使用jdbc中的事务 -->
            <transactionManager type="JDBC"></transactionManager>         
            <!-- 配置数据源 -->
            <dataSource type="POOLED">
                 <property name="driver" value="${driver}"/>
                 <property name="url" value="${url}"/>
                 <property name="username" value="${username}"/>
                 <property name="password" value="${password}"/>
            </dataSource>
            
            
         </environment>
    </environments>
    
    
    <mappers>
        <mapper resource="cn/zzsxt/entity/TbUser.xml"/>
    </mappers>
</configuration>  

  TbUserDao.java:

package cn.zzsxt.dao;

import java.util.List;

import cn.zzsxt.entity.TbUser;

public interface TbUserDao {
    public List<TbUser> findAll();
    public TbUser findUserById(Long id);
    public int addUser(TbUser user);
    public int updateUser(TbUser user);
    public int deleteUser(long id);
}

  TbUserDaoImpl.java:

package cn.zzsxt.dao.impl;

import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import cn.zzsxt.dao.TbUserDao;
import cn.zzsxt.entity.TbUser;

public class TbUserDaoImpl implements TbUserDao {

    @Override
    public List<TbUser> findAll() {
        //加载全局配置文件
        InputStream ips = this.getClass().getResourceAsStream("/mybatis-config.xml");
        //创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);
        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //执行查询
        List<TbUser> list = sqlSession.selectList("user.findAll");//参数为映射文件中的statment id
        //释放资源
        sqlSession.close();
        return list;
    }

    @Override
    public TbUser findUserById(Long id) {
        //加载全局配置文件
        InputStream ips = this.getClass().getResourceAsStream("/mybatis-config.xml");
        //创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);
        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //执行查询
        TbUser user =  sqlSession.selectOne("user.findUserById",id);
        sqlSession.close();
        return user;
    }

    @Override
    public int addUser(TbUser user) {
        //加载全局配置文件
        InputStream ips = this.getClass().getResourceAsStream("/mybatis-config.xml");
        //创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);
        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //执行查询
        int count = sqlSession.insert("user.addUser", user);
        //提交事务
        sqlSession.commit();
//        sqlSession.rollback();//回滚事务
        sqlSession.close();
        return count;
    }

    @Override
    public int updateUser(TbUser user) {
        //加载全局配置文件
        InputStream ips = this.getClass().getResourceAsStream("/mybatis-config.xml");
        //创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);
        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //执行查询
        int count = sqlSession.update("user.updateUser", user);
        //提交事务
        sqlSession.commit();
        sqlSession.close();
        return count;
    }

    @Override
    public int deleteUser(long id) {
        //加载全局配置文件
        InputStream ips = this.getClass().getResourceAsStream("/mybatis-config.xml");
        //创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);
        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //执行查询
        int count = sqlSession.update("user.deleteUser", id);
        //提交事务
        sqlSession.commit();
        sqlSession.close();
        return count;
    }

}

  TbUser.java:

package cn.zzsxt.entity;

import java.io.Serializable;
import java.util.Date;

public class TbUser implements Serializable{
    private long id;
    private String username;
    private String sex;
    private Date birthday;
    private String address;
    
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "TbUser [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="
                + address + "]";
    }
    
}

  TbUser.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">
<!-- 
1.User.xml(原始ibatis命名),mapper代理开发的映射文件命名XxxMapper.xml
2.namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离
3.注意:使用mapper代理开发,namespace有特殊的作用
 -->        
<mapper namespace="user">
    <!--在映射文件中配置很多sql语句-->
    <!--需求:通过id查询用户表的记录-->
    <!--
        1.标识映射文件中的sql,将sql语句封装到mapped statement对象中,所以称为statement的id
        2.parameterType:指定输入参数类型
        3.#{}:表示一个占位符
        4.#{id}:其中的id表示接收的输入参数,参数名称就是id,如果输入参数是简单类型,#{}中的参数名可以任意,可以为value或者其他
        5.resultType:指定sql输出结果的所映射的java对象类型,select指定resultType表示将单条记录映射成的java对象
    -->
    <!-- 查询 -->
    <select id="findAll" resultType="cn.zzsxt.entity.TbUser">
        select * from tb_user
    </select>
    
    <select id="findUserById" parameterType="java.lang.Long" resultType="cn.zzsxt.entity.TbUser">
        select * from tb_user where id=#{id}
    </select>
    
    
    <!-- 添加 -->
    <insert id="addUser" parameterType="cn.zzsxt.entity.TbUser">
        insert into tb_user(username,sex,birthday,address) values(#{username},#{sex},#{birthday},#{address})
    </insert>
    
    
    <!-- 修改 -->
    <update id="updateUser" parameterType="cn.zzsxt.entity.TbUser">
        update tb_user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}
    </update>
    
    
    <!-- 删除 -->
    <delete id="deleteUser" parameterType="java.lang.Long">
        delete from tb_user where id=#{id}
    </delete>
</mapper>

  Test1.java:

package cn.zzsxt.demo;

import java.util.Date;
import java.util.List;

import org.junit.Test;

import cn.zzsxt.dao.TbUserDao;
import cn.zzsxt.dao.impl.TbUserDaoImpl;
import cn.zzsxt.entity.TbUser;

public class Test1 {
    
    @Test
    public void testFindAll(){
        TbUserDao tbUserDao = new TbUserDaoImpl();
        List<TbUser> list = tbUserDao.findAll();
        for (TbUser tbUser : list) {
            System.out.println(tbUser);
        }
    }
    
    @Test
    public void testFindUserById(){
        TbUserDao tbUserDao = new TbUserDaoImpl();
        TbUser user = tbUserDao.findUserById(new Long(1));
        System.out.println(user);
    }
    
    @Test
    public void testAddUser(){
        TbUserDao tbUserDao = new TbUserDaoImpl();
        TbUser user = new TbUser();
        user.setUsername("test");
        user.setSex("男");
        user.setBirthday(new Date());
        user.setAddress("北京");
        int count = tbUserDao.addUser(user);
        System.out.println(count);
    }
    
    @Test
    public void testUpdateUser(){
        TbUserDao tbUserDao = new TbUserDaoImpl();
        TbUser user = tbUserDao.findUserById(4L);
        user.setUsername("王五");
        int count =tbUserDao.updateUser(user);
        System.out.println(count);
    }
    
    @Test
    public void testDeleteUser(){
        TbUserDao tbUserDao = new TbUserDaoImpl();
        int count =tbUserDao.deleteUser(4L);
        System.out.println(count);
    }
}
 

  TestLog4J.java:

package cn.zzsxt.test;

import org.apache.log4j.Logger;
import org.junit.Test;

public class TestLog4J {
    
    Logger logger = Logger.getLogger(TestLog4J.class.getName());
    @Test
    public void test01(){
//        System.out.println("xxxx");
        logger.debug("debug....");
        logger.info("info....");
        logger.warn("warn....");
        logger.error("error....");
        logger.fatal("fatal....");
    }
    
    public static void main(String[] args) {
        TestLog4J test = new TestLog4J();
        test.test01();
    }
    
    
}

 

java:Mybatis框架1(基本配置,log4j)

标签:update   style   interface   on()   pool   bug   main   override   names   

原文地址:http://www.cnblogs.com/kuangzhisen/p/7460369.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!