亚洲精品久久国产精品37p,亚洲av无码av制服另类专区,午夜直播免费看,玩弄人妻少妇500系列视频,无码人妻久久久一区二区三区

MyBatis入門

MyBatis入門


1.環(huán)境搭建

  • https://GitHub.com/mybatis-3/releases 下載

  • ① maven依賴

    <!--MyBatis 3.4.2 -->
    <dependency>
    	<groupId>org.mybatis</groupId>
    	<artifactId>mybatis</artifactId>
    	<version>3.4.2</version>
    </dependency>
    
    <!--MySQL -->
    <dependency>
    	<groupId>mysql</groupId>
    	<artifactId>mysql-connector-java</artifactId>
    	<version>5.1.35</version>
    </dependency>
    

    解決無(wú)法識(shí)別xml配置文件

    <build>
    	<resources>
    		<resource>
                <!--<directory>src/test/java</directory>-->
    			<directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>
    

    ② 導(dǎo)入mybatis-3.4壓縮包中的lib下的所有jar包

  • 由于MyBatis默認(rèn)使用log4j輸出日志信息,在類路徑下建立 log4j.properties

    # Global logging configuration
    log4j.rootLogger=ERROR, stdout
    # MyBatis logging configuration... 下行可更改
    log4j.logger.com.itheima=DEBUG
    # Console output...
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
    

  • 存儲(chǔ)變量文件db.properties

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

  • 建立映射文件

    <?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.itheima.mapper.CustomerMapper">
        <!--抽出重復(fù)代碼-->
        <sql id="customerColumns">id,username,jobs,phone</sql>
        <!--通過(guò)id查詢用戶-->
        <select id="findCustomerById" parameterType="Integer" resultType="com.itheima.po.Customer">
            select <include refid="customerColumns"/>
            from t_customer where id = #{id}
        </select>
    </mapper>
    

  • 建立核心配置文件 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="mysql">
            <environment id="mysql">
                <!--使用JDBC事務(wù)管理-->
                <transactionManager type="JDBC"/>
                <!--數(shù)據(jù)庫(kù)連接池-->
                <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>
            <mapper resource="com/itheima/mapper/CustomerMapper.xml"/>
        </mappers>
    </configuration>
    

  • 工具類創(chuàng)建SqlSession

    public class MybatisUtils {
        private static SqlSessionFactory sqlSessionFactory = null;
        static{
            try{
                Reader reader =
                        Resources.getResourceAsReader("mybatis-config.xml");
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        public static SqlSession getSession(){
            return sqlSessionFactory.openSession();
        }
    }
    

  • 測(cè)試程序(查詢單個(gè)用戶)

    SqlSession sqlSession = MybatisUtils.getSession();
    Customer customer = sqlSession.selectOne("com.itheima.mapper"
            + ".CustomerMapper.findCustomerById", 1);
    System.out.println(customer.toString());
    sqlSession.close();
    

2.入門程序

1.模糊查詢多個(gè)用戶

<select id="findCustomerByName" parameterType="String"
		resultType="com.itheima.po.Customer">
	<!--select * from t_customer where username like '%${value}%' 下方防注入-->
	select * from t_customer where username like concat('%',#{value},'%')
</select>
List<Customer> customers = sqlSession.selectList("com.itheima.mapper"
        + ".CustomerMapper.findCustomerByName", "j");
for(Customer customer: customers){
    System.out.println(customer);
}
sqlSession.close();

2.添加用戶

<insert id="addCustomer" parameterType="com.itheima.po.Customer"
        keyProperty="id" useGeneratedKeys="true">
    insert into t_customer(username,jobs,phone)
    values (#{username},#{jobs},#{phone})
</insert>
SqlSession sqlSession = MybatisUtils.getSession();
Customer customer = new Customer();
customer.setUsername("rose");
customer.setJobs("student");
customer.setPhone("13333533092");
int rows = sqlSession.insert("com.itheima.mapper"
		+".CustomerMapper.addCustomer",customer);
System.out.println(customer.getId());
if(rows>0){
	System.out.println("插入了"+rows+"條數(shù)據(jù)");
}else{
	System.out.println("插入失敗");
}
sqlSession.commit();
sqlSession.close();

3.修改信息

<update id="updateCustomer" parameterType="com.itheima.po.Customer">
	update t_customer set
	username=#{username},jobs=#{jobs},phone=#{phone}
	where id=#{id}
</update>
SqlSession sqlSession = MybatisUtils.getSession();
Customer customer = new Customer();
customer.setId(6);
customer.setUsername("rose");
customer.setJobs("programmer");
customer.setPhone("13311111111");
int rows = sqlSession.update("com.itheima.mapper"
        	+ ".CustomerMapper.updateCustomer", customer);
if(rows>0){
	System.out.println("修改了"+rows+"條數(shù)據(jù)");
}else{
	System.out.println("修改失敗");
}
sqlSession.commit();
sqlSession.close();

4.刪除用戶

<update id="updateCustomer" parameterType="com.itheima.po.Customer">
	update t_customer set
	username=#{username},jobs=#{jobs},phone=#{phone}
	where id=#{id}
</update>
int rows = sqlSession.delete("com.itheima.mapper"
        	+ ".CustomerMapper.deleteCustomer", 6);
if(rows>0){
	System.out.println("刪除了"+rows+"條數(shù)據(jù)");
}else{
	System.out.println("刪除失敗");
}
sqlSession.commit();
sqlSession.close();

3.Mapper接口

SqlSession還有一個(gè)getMapper()方法用于訪問(wèn)Mybatis ,這個(gè)方法需要使用Mapper接口

Mapper接口規(guī)范

  1. Mapper接口名稱與Mapper.xml名稱必須一致
  2. Mapper接口的類路徑和Mapper.xml映射文件相同
  3. 接口中的方法與xml中的id相同
  4. 方法的輸入要和parameterType類型相同
  5. 輸出要和resultType相同(如果使用了resultMap則與resultMap中的Type屬性相同)

將上面配置文件寫為Mapper接口形式

public interface CustomerMapper {
    public Customer findCustomerById(Integer id);
    public List<Customer> findCustomerByName(String name);
    public int addCustomer(Customer customer);
    public int updateCustomer(Customer customer);
    public int deleteCustomer(Integer id);
}

程序調(diào)用方式

@Test
public void findCusByMapper(){
	SqlSession sqlSession = MybatisUtils.getSession();
	CustomerMapper customerMapper = sqlSession.getMapper(CustomerMapper.class);
	List<Customer> customers = customerMapper.findCustomerByName("j");
	for(Customer c:customers){
	System.out.println(c);
	}
	sqlSession.close();
}

評(píng)論(0條)

刀客源碼 游客評(píng)論