• Mybaits入门使用


    1.pom.xml配置信息

    <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.1.1</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.38</version>
            </dependency>
        </dependencies>
    

      测试类:

    public class Person {
        private int id;
        private String name;
        private int age;
        private String address;
        private String birthday;
    
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public String getAddress() {
            return address;
        }
        public void setAddress(String address) {
            this.address = address;
        }
        public String getBirthday() {
            return birthday;
        }
        public void setBirthday(String birthday) {
            this.birthday = birthday;
        }
        @Override
        public String toString() {
            return "Person [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + ", birthday="
                    + birthday + "]";
        }
    }
    

      sql语句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="test1">
    	<select id="querypersonbyid" parameterType="int" resultType="person">
    		select id,name,age,birthday,address from Person where id = #{value}
    	</select>
    	
    	<select id="querypersonbyname" parameterType="java.lang.String" resultType="person">
    		select id,name,age,birthday,address from Person where name like "%${value}%"
    	</select>
    	
    	<insert id="inserperson" parameterType="person">
    		<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
    			SELECT LAST_INSERT_ID()
    		</selectKey>
    		insert into Person(name,age,address,birthday) value(#{name},#{age},#{address},#{birthday})
    	</insert>
    	
    	<delete id="deletepersonbyid" parameterType="int">
    		delete from Person where id = #{id}
    	</delete>
    	
    	<delete id="updatepersonbyid" parameterType="person">
    		update Person set name=#{name},age=#{age},birthday=#{birthday},address=#{address} where id = #{id}
    	</delete>
    	
    </mapper>
    

     数据库访问配置:

    <?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">  
            <!--properties中还可以配置一些属性名和属性值 -->  
            <!-- <property name="jdbc.driver" value=""/> -->  
        </properties>  
      
        <typeAliases>  
            <!-- 别名定义 -->
            <typeAlias type="com.youfan.entity.Person" alias="person" />
        </typeAliases>  
      
        <environments default="development">  
            <environment id="development">  
                <!-- 使用jdbc事务管理,事务控制由mybatis -->  
                <transactionManager type="JDBC" />  
                <!-- 数据库连接池,由mybatis管理 -->  
                <dataSource type="POOLED">  
                    <property name="driver" value="${jdbc.driver}" />  
                    <property name="url" value="${jdbc.url}" />  
                    <property name="username" value="${jdbc.username}" />  
                    <property name="password" value="${jdbc.password}" />  
                </dataSource>  
            </environment>  
        </environments>  
      
      
        <!-- 加载 映射文件 -->  
        <mappers>
            <!--通过resource方法一次加载一个映射文件 -->  
                    <!--注意这里的路径和xml文件 -->  
                   <mapper resource="Person.xml" />
              
        </mappers>  
      
    </configuration>
    TestMybatis:
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    import com.sun.org.apache.xpath.internal.SourceTree;
    import com.youfan.entity.Person;
    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 org.junit.Test;
    
    
    import java.io.InputStream;
    
    public class TestMybatis {
        public SqlSessionFactory getfactory() throws IOException {
            String filepath="SqlMappingConfig.xml";
            InputStream in = Resources.getResourceAsStream(filepath);
           SqlSessionFactory sqlSessionFactory=new  SqlSessionFactoryBuilder().build(in);
           return sqlSessionFactory;
        }
        @Test
        public void testinsert() throws IOException {
            SqlSessionFactory sqlSessionFactory = this.getfactory();
            SqlSession sqlsession = sqlSessionFactory.openSession();
            Person person = new Person();
            person.setName("小高");
            person.setAddress("上海");
            person.setAge(15);
            person.setBirthday("05-04");
            sqlsession.insert("test1.inserperson", person);
            System.out.println("id "+person.getId());
            sqlsession.commit();
            sqlsession.close();
        }
    
        @Test
        public void testquerybyid() throws IOException{
            SqlSessionFactory sqlSessionFactory = this.getfactory();
            SqlSession sqlsession = sqlSessionFactory.openSession();
            Person person = sqlsession.selectOne("querypersonbyid", 6);
            System.out.println(person);
            sqlsession.close();
        }
        @Test
        public void testquerybyname() throws IOException{
            SqlSessionFactory sqlSessionFactory = this.getfactory();
            SqlSession sqlsession = sqlSessionFactory.openSession();
            List<Person> personlist = sqlsession.selectList("querypersonbyname", "小高");
            for(int i=0;i<personlist.size();i++){
                System.out.println(personlist.get(i));
            }
            sqlsession.close();
        }
    
        @Test
        public void testdeletebyid() throws IOException{
            SqlSessionFactory sqlSessionFactory = this.getfactory();
            SqlSession sqlsession = sqlSessionFactory.openSession();
            sqlsession.delete("deletepersonbyid", 6);
            sqlsession.commit();
            sqlsession.close();
        }
    
        @Test
        public void testupdatePerson() throws IOException{
            SqlSessionFactory sqlSessionFactory = this.getfactory();
            SqlSession sqlsession = sqlSessionFactory.openSession();
            Person person = new Person();
            person.setId(2);
            person.setName("有范");
            person.setAddress("北京");
            person.setAge(15);
            person.setBirthday("06-04");
            sqlsession.update("updatepersonbyid", person);
            sqlsession.commit();
            sqlsession.close();
        }
    } 

    表字段: 

     用映射方法写:

    mapper:

    public interface PersonMapper {
    	public Person querypersonbyid(int id);
    	public List<Person> querypersonbyname(String name);
    	public void inserperson(Person person);
    	public void deletepersonbyid(int id);
    	public void updatepersonbyid(Person person);
    	public List<Person> querypersonbyvo(PersonVo personVo);
    }
    

      视图对象vo:

    public class CustomPerson extends Person{
    
    }
    

      

    public class PersonVo {
    	private CustomPerson customPerson;
    
    	public CustomPerson getCustomPerson() {
    		return customPerson;
    	}
    
    	public void setCustomPerson(CustomPerson customPerson) {
    		this.customPerson = customPerson;
    	}
    	
    }
    

     语句:

    <?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.youfan.mapper.PersonMapper">
    	<sql id="consutomsql" >
    		<if test="customPerson != null">
    			<if test="customPerson.name!=null and customPerson.name!=''">
    					and name = "${customPerson.name}"
    				</if>
    				<if test="customPerson.birthday!=null and customPerson.birthday!='' ">
    					and birthday = "${customPerson.birthday}"
    			</if>
    		</if>
    	</sql>
    	<select id="querypersonbyvo" parameterType="personVo" resultType="person">
    	select * from Person
    		<where>
    			<include refid="consutomsql"></include>
    		</where>
    	</select>
    	<select id="querypersonbyid" parameterType="int" resultType="person">
    		select id,name,age,birthday,address from Person where id = #{value}
    	</select>
    	
    	<select id="querypersonbyname" parameterType="java.lang.String" resultType="person">
    		select id,name,age,birthday,address from Person where name like "%${value}%"
    	</select>
    	
    	<insert id="inserperson" parameterType="person">
    		<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
    			SELECT LAST_INSERT_ID()
    		</selectKey>
    		insert into Person(name,age,address,birthday) value(#{name},#{age},#{address},#{birthday})
    	</insert>
    	
    	<delete id="deletepersonbyid" parameterType="int">
    		delete from Person where id = #{id}
    	</delete>
    	
    	<delete id="updatepersonbyid" parameterType="person">
    		update Person set name=#{name},age=#{age},birthday=#{birthday},address=#{address} where id = #{id}
    	</delete>
    	
    </mapper>
    

      测试:

    public class TestMybatis {
    	public SqlSessionFactory getfactory() throws IOException{
    		String filepath = "SqlMappingConfig.xml";
    		InputStream in = Resources.getResourceAsStream(filepath);
    		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
    		return sqlSessionFactory;
    	}
    
    	@Test
    	public void testinsert() throws IOException{
    		SqlSessionFactory sqlSessionFactory = this.getfactory();
    		SqlSession sqlsession = sqlSessionFactory.openSession();
    		PersonMapper personMapper = sqlsession.getMapper(PersonMapper.class);
    		Person person = new Person();
    		person.setName("小白");
    		person.setAddress("上海");
    		person.setAge(15);
    		person.setBirthday("05-04");
    		personMapper.inserperson(person);
    		System.out.println("id "+person.getId());
    		sqlsession.commit();
    		sqlsession.close();
    	}
    
    	@Test
    	public void testquerybyid() throws IOException{
    		SqlSessionFactory sqlSessionFactory = this.getfactory();
    		SqlSession sqlsession = sqlSessionFactory.openSession();
    		PersonMapper personMapper = sqlsession.getMapper(PersonMapper.class);
    		Person person = personMapper.querypersonbyid(2);
    		System.out.println(person);
    		sqlsession.close();
    	}
    
    	@Test
    	public void testquerybyname() throws IOException{
    		SqlSessionFactory sqlSessionFactory = this.getfactory();
    		SqlSession sqlsession = sqlSessionFactory.openSession();
    		PersonMapper personMapper = sqlsession.getMapper(PersonMapper.class);
    		List<Person> personlist = personMapper.querypersonbyname("小");
    		for(int i=0;i<personlist.size();i++){
    			System.out.println(personlist.get(i));
    		}
    		sqlsession.close();
    	}
    
    	@Test
    	public void testdeletebyid() throws IOException{
    		SqlSessionFactory sqlSessionFactory = this.getfactory();
    		SqlSession sqlsession = sqlSessionFactory.openSession();
    		PersonMapper personMapper = sqlsession.getMapper(PersonMapper.class);
    		personMapper.deletepersonbyid(2);
    		sqlsession.commit();
    		sqlsession.close();
    	}
    
    	@Test
    	public void testupdatePerson() throws IOException{
    		SqlSessionFactory sqlSessionFactory = this.getfactory();
    		SqlSession sqlsession = sqlSessionFactory.openSession();
    		PersonMapper personMapper = sqlsession.getMapper(PersonMapper.class);
    		Person person = new Person();
    		person.setId(3);
    		person.setName("老石");
    		person.setAddress("北京");
    		person.setAge(15);
    		person.setBirthday("07-04");
    		personMapper.updatepersonbyid(person);
    		sqlsession.commit();
    		sqlsession.close();
    	}
    
    	@Test
    	public void testquerypersonbyvo() throws IOException{
    		SqlSessionFactory sqlSessionFactory = this.getfactory();
    		SqlSession sqlsession = sqlSessionFactory.openSession();
    		PersonMapper personMapper = sqlsession.getMapper(PersonMapper.class);
    		PersonVo personVo = new PersonVo();
    		CustomPerson customPerson = new CustomPerson();
    		customPerson.setName("老石");
    		customPerson.setBirthday("07-04");
    		personVo.setCustomPerson(customPerson);
    		List<Person> personlist = personMapper.querypersonbyvo(personVo);
    		for(int i=0;i<personlist.size();i++){
    			System.out.println(personlist.get(i));
    		}
    		sqlsession.close();
    	}
    }
    

      

     

  • 相关阅读:
    python 命令行传参
    chardet模块下载&安装
    【解决方案】编码问题:UnicodeDecodeError: 'XXX' codec can't decode byte 0xad in position...的错误
    [解决方案]Python脚本运行出现语法错误:IndentationError: unindent does not match any outer indentation level
    perl笔记
    字符串操作
    c++错误及解决方案随记
    本地Java程序访问HTTPs遇到的问题
    学习笔记 : 异常处理
    学习笔记 : python 文件操作
  • 原文地址:https://www.cnblogs.com/sunliyuan/p/10718163.html
Copyright © 2020-2023  润新知