框架:
含義:半成品的軟件。即這個框架幫我我們寫了一部分代碼,我們用這個框架,就需要按這個框架的規則來把我們要完成的任務(軟件)來補充完整。框架幫我們完成的那部分代碼一般包括(類型裝換,加載配置文件等)。
框架的一般步驟:
- 導包(即框架幫我們實現的那部分代碼)
- 編寫配置文件(通常分爲位置固定,名字固定,或兩者都或兩者都不。如果是兩者都不的話,肯定需要我們自己動手來加載配置文件)
- 編寫業務代碼(我們實現功能,需要自己寫的代碼)
框架的底層實現:
java的反射機制是框架的基礎。java的設計模式常會被用到框架中(如:工廠設計模式,單例設計模式,構建者設計模式等等)
Mybatis框架:
一種持久化框架但不是ORM框架
步驟:
1.導包:
2.編寫Mybatis.xml文件(通常放在src下,它是位置不固定名字不固定的配置文件)它是數據庫配置文件。
<?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>
<environments default="default">
<environment id="default">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/daily"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.mapper"/>
</mappers>
</configuration>
3.編寫UserMapper.xml文件,放在以Mapper結尾的包中,它是映射文件,負責把數據庫的表映射生成類。
<?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.mapper.UserMapper">
<select id="selall" resultType="com.pojo.User" parameterType="int">
select * from user where id=#{0}
</select>
<resultMap type="com.pojo.User" id="usermap">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="password" column="password"/>
<collection property="list" select="com.mapper.PlanMapper.selbyid" column="id"></collection>
</resultMap>
<select id="sel" resultMap="usermap">
select * from user
</select>
<insert id="ins" parameterType="com.pojo.User" >
insert into user value (default,#{name},#{password})
</insert>
<delete id="del" parameterType="int" >
delete from user where id = #{0}
</delete>
<delete id="delall" parameterType="int">
delete from user where id = #{0}
<if test="1==1">
<!-- 級聯刪除!!! -->
</if>
</delete>
</mapper>
4.編寫Test測試文件,但是一般在一個項目中一般不會有這一步,例如在spring-mybatis框架中,Test測試文件會由Spring部分代替。
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = factory.openSession();
PlanMapper plan = session.getMapper(PlanMapper.class);
int s = plan.delplan(4);
session.commit();
session.close();