- 新建Java项目IbatisTest,加入Mysql和ibatis的驱动包;
- 在数据库中新建一张表student表,添加字段sid、sname、major、birth;
- 在java项目中添加bean对象Student,新建一个IStudentDAOImpl接口,新建StudentDAO(实现IStudentDAOImpl接口)来操作数据库;
- 配置SqlMapConfig.xml文件;配置如下:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" "http://www.ibatis.com/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <properties resource ="Ibatis/config/SqlMap.properties"/> <settings cacheModelsEnabled ="true" <!--cacheModelsEnabled是否启用缓存机制--> lazyLoadingEnabled="true" <!--lazyLoadingEnabled是否启用延迟加载机制--> enhancementEnabled="true" <!--enhancementEnabled是否启用字节码增强机制--> errorTracingEnabled="true" <!--errorTracingEnabled是否启用错误处理机制--> maxRequests="32" <!--maxRequests最大并发请求数--> maxSessions="10" <!--maxSessions最大Session数--> maxTransactions="5" <!--maxTransactions最大并发事务数--> useStatementNamespaces="true"/><!--useStatementNamespaces是否启用名称空间--> <transactionManager type ="JDBC"><!-- 定义了ibatis的事务管理器有3中(JDBC,JTA,EXTERNAL) --> <dataSource type ="SIMPLE"><!-- type属性指定了数据源的链接类型,也有3种类型(SIMPLE,DBCP,JNDI) --> <property name ="JDBC.Driver" value="${driver}"/> <property name ="JDBC.ConnectionURL" value="${url}"/> <property name ="JDBC.Username" value="${username}"/> <property name ="JDBC.Password" value="${password}"/> <property name ="Pool.MaximumActiveConnections" value ="10"/><!--Pool.MaximumActiveConnections连接池维持的最大容量 --> <property name ="Pool.MaximumIdleConnections" value ="5"/> <!--Pool.MaximumIdleConnections连接池允许挂起的最大连接 --> <property name ="Pool.MaximumCheckoutTime" value ="120000"/> <!--Pool.MaximumCheckoutTime连接被某个任务所允许占用的最大时间 --> <property name ="TimeToWait" value ="500"/> <!--TimeToWait线程允许等待的最大时间 --> </dataSource > </transactionManager > <sqlMap resource ="Ibatis/Map/Student.xml"/> </sqlMapConfig >
注:(1)这里为了便于后期便于修改数据库的配置,添加了一个配置数据库信息的属性文件;
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost/test username=root password =root
(2)由于ibatis要求xml文件中几个主要的结点按顺序排放,不然在解析xml的时候会报错。
- 配置数据库映射文件Student.xml;
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-config-2.dtd" > <sqlMap> <typeAlias alias ="Student" type="Ibatis.model.Student"/> <select id="selectAllStudent" resultClass="Student"> select * from student </select> <select id="queryStudentById" parameterClass="int" resultClass="Student"> select * from student where sid =#sid# </select> <select id="queryStudentByName" parameterClass="String" resultClass="Student"> select * from student where sname like '%$sname$%' </select> <insert id="insertStudent" parameterClass="Student"> insert into Student (sname,major,birth) values(#sname#,#major#,#birth#) </insert> <delete id="deleteStudentbyId" parameterClass="int"> delete from student where sid = #sid# </delete> <update id="updateStudent" parameterClass = "Student"> update student set sname=#sname#,major=#major#,birth=#birth# </update> </sqlMap>
Ibatis的环境搭建以及遇到的问题解决
最新推荐文章于 2024-08-16 18:39:05 发布