竞争无处不在,青春永不言败!专业撸代码,副业修bug

Talk is cheap , show me the code!



mybatis 不整合spring 入门小例子

先上一个搭建完的项目结构截图:

 

相对比较重要的配置文件有 db.properties , SqlMappingConfig.xml , mapper/User.xml , log4j.properties (主要是 mybatis 有日志管理这些依赖 后面 pom.xml 中也要添加 log4j 的jar  包依赖)

jdbc.driver=com.mysql.jdbc.Driver  
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=UTF-8  
jdbc.username=root  
jdbc.password=Mede645
db.properties
<?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="config/db.properties">
        <!--properties中还可以配置一些属性名和属性值 -->
        <!-- <property name="jdbc.driver" value=""/> -->
    </properties>

    <!-- 全局配置参数,需要时再设置 -->
    <!-- <settings> </settings> -->

    <typeAliases>
        <!-- 别名定义 -->
        <!-- 针对单个别名定义 type:类型的路径 alias:别名 -->
        <!-- <typeAlias type="cn.czy.mybatis.po.User" alias="user"/> -->
        <typeAlias type="com.ghc.pojo.User" alias="user" />
        <!-- 批量别名定义 指定包名,mybatis自动扫描包中的po类,自动定义别名,别名就是类名(首字母大写或小写都可以) -->
        <!--<package name="cn.com.mybatis.mapper" />-->
    </typeAliases>

    <!-- 和spring整合后 environments配置将废除 -->
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc事务管理,事务控制由mybatis -->
            <transactionManager type="JDBC" />
            <!-- 数据库连接池,由mybatis管理 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=UTF-8" />
                <property name="username" value="root" />
                <property name="password" value="Mede645" />
            </dataSource>
        </environment>
    </environments>


    <!-- 加载 映射文件 -->
    <mappers>


        <!--通过resource方法一次加载一个映射文件 -->
        <!--注意这里的路径和xml文件 -->
        <mapper resource="mapper/User.xml" />
   <!--     <mapper resource="mapper/userMapper.xml" />
        <mapper resource="mapper/OrdersMapperCustom.xml"/>-->

        <!-- 批量加载mapper 指定mapper接口的包名,mybatis自动扫描包下边所有mapper接口进行加载 -->
        <!-- 遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录 -->
        <!-- 中 上边规范的前提是:使用的是mapper代理方法
        <package name="cn.com.czy.mybatis.two.mapper" />-->

    </mappers>

</configuration>
SqlMappingConfig.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">

<mapper namespace="test">

    <!-- 在 映射文件中配置很多sql语句 -->
    <!-- 将sql语句封装到mappedStatement对象中,所以将id称为statement的id -->
    <!-- parameterType:指定输入 参数的类型,这里指定int型 #{}表示一个占位符号 -->
    <!-- #{id}:其中的id表示接收输入 的参数,参数名称就是id,如果输入 -->
    <!-- 参数是简单类型,#{}中的参数名可以任意,可以value或其它名称 -->
    <!-- resultType:指定sql输出结果 的所映射的java对象类型,select指定resultType表示将单条记录映射成的java对象。 -->
    <select id="findUserById" parameterType="int"  resultType="user">
        SELECT * FROM USER WHERE id=#{value}
    </select>

    <select id="findUserByNameLike" parameterType="java.lang.String" resultType="user">
        SELECT * FROM USER WHERE USERNAME LIKE '%${value}%'
    </select>

    <!--OGNL 获取对象的属性值-->
    <insert id="addUser" parameterType="user">
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
        select last_insert_id()
    </selectKey>
        INSERT INTO user(username,birthday,sex,address) values(#{userName},#{birthday},#{sex},#{address})
    </insert>

    <!--删除用户-->
    <delete id="deleteUser" parameterType="java.lang.Integer">
        delete from USER  where id = #{id}
    </delete>

    <!--更新用户-->
    <update id="updateUser" parameterType="user">
        update  User  set  username=#{userName},sex=#{sex} where id=#{id}
    </update>
</mapper>
User.xml
log4j.rootLogger=DEBUG,A1
log4j.logger.org.springframework=debug
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d %5p [%t] (%F:%L) - %m%n
log4j.properties
package com.ghc.pojo;

import java.util.Date;

public class User {
   private int id;
   private String userName;
   private Date birthday;
   private String sex;
   private String address;

    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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
pojo对象User代码

下面是比较重要的 怎么读取配置文件然后映射数据库了 测试了

package com.ghc.main;

import com.ghc.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.io.IOException;
import java.io.InputStream;

public class Test {

    public  SqlSessionFactory getSqlSessionFactory() throws IOException{
        // mybatis 配置文件
        String mybatisConfigFile = "config/SqlMappingConfig.xml";

        InputStream inputStream = Resources.getResourceAsStream(mybatisConfigFile);


        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return sqlSessionFactory;

    }

    public static void main(String [] args) throws Exception{
        new Test().findUserByName();//.findUserById();
        new Test().insertUser();
        new Test().deleteUser();
        new Test().updateUser();

    }

    public  void findUserById(){
        SqlSession sqlSession = null;
        try {
            sqlSession = this.getSqlSessionFactory().openSession();
            User user = sqlSession.selectOne("test.findUserById",10);
            System.out.println("user name: "+user.getUserName());
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally{if(sqlSession!=null)
        try{
            sqlSession.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }}

    }

    public List<User> findUserByName() throws Exception{
        List<User> userList = new ArrayList<User>();
        SqlSession sqlSession = this.getSqlSessionFactory().openSession();
        userList = sqlSession.selectList("test.findUserByNameLike","小明");
        for(User user:userList){
            System.out.println(user.getUserName());
        }
        sqlSession.close();
        return userList;
    }

    public void insertUser() throws IOException{
        User user = new User();
        //user.setId(42);
        int temp = user.getId();
        user.setAddress("麓谷");
        user.setBirthday(new Date());
        user.setSex("女");
        user.setUserName("王老五");
        SqlSession sqlSession = this.getSqlSessionFactory().openSession();
        sqlSession.insert("test.addUser",user);
        sqlSession.commit();
        sqlSession.close();
    }

    public void deleteUser() throws IOException{
        SqlSession sqlSession = this.getSqlSessionFactory().openSession();
        sqlSession.delete("test.deleteUser",42);
        sqlSession.commit();
        sqlSession.close();
    }

    public void updateUser()throws IOException{
        SqlSession sqlSession = this.getSqlSessionFactory().openSession();
        User user = new User();
        user.setUserName("钻石王老五");
        user.setId(43);
        user.setSex("男");
        sqlSession.update("test.updateUser",user);
        sqlSession.commit();
        sqlSession.close();
    }
}
com.ghc.main.Test

 

下一篇我将代入 dao 层开发

posted @ 2018-04-17 09:27  云雾散人  阅读(447)  评论(0编辑  收藏  举报

Your attitude not your aptitude will determine your altitude!

如果有来生,一个人去远行,看不同的风景,感受生命的活力!