1. 程式人生 > >java:Mybatis框架1(基本配置,log4j)

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

屬性 apache led sta sql inpu ack ima 文件中

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)