工具包:
Netbeans8
Maven
MyBatis
- 使用netbeans创建项目,选择文件->新建项目->Maven->Web应用程序;
- 打开项目目录,在依赖关系上右击->添加依赖关系->查询框输入mysql->选择mysql:mysql-connector-java->点开选择对应的mysql驱动版本.
- 创建数据库和表
create database foretaste; use foretaste create table user_info(id int(11) not null primary key auto_increment, nickname varchar(50) not null, phone_num int(11) not null, created_time timestamp not null default current_timestamp, last_update_time timestamp not null default current_timestamp);
4. 点开->项目的其他源->src/main/source,在默认包上右击,xml文件,命名为mybatis-config.xml
<environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/foretaste?zeroDateTimeBehavior=convertToNull "/> <property name="username" value="root"/> <property name="password" value="mysql123"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com.shadow.foretaste.UserInfoMapper.xml"/> </mappers>
5. 新建User实体类,新建com.shadow.foretaste.entity包,创建UserInfo实体类
6. 在source文件下,新建mapper文件夹,并创建UserInfoMapper.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"> <mapper namespace="com.shadow.foretaste.UserInfoMapper"> <insert id="insert" parameterType="com.shadow.foretaste.entity.UserInfo" useGenerateKeys="true"> insert_into user_nfo (nickname, phone_num, created_time, last_update_time) values (#{nickname}, #{phone_num}, #{created_time), #{last_update_time}) </insert> <select id ="select" resultType="com.shadow.foretaste.entity.UserInfo"> select * from user_info </select> </mapper>
7. 创建MyBatisUtils获取sqlSession
package com.shadow.foretaste.util; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; /** * * @author sunny */ public class MyBatisUtils { private static SqlSessionFactory factory = null; //初始化session工厂 public static void initFactory() throws Exception{ InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); factory = new SqlSessionFactoryBuilder().build(inputStream); } /** * 获取sqlSession会话 * @return */ public static SqlSession getSession(){ if(null == factory){ try { initFactory(); } catch (Exception ex) { ex.printStackTrace(); } } return factory.openSession(); } }
8. 创建测试方法验证配置
import com.shadow.foretaste.util.MyBatisUtils; import org.apache.ibatis.session.SqlSession; import static org.junit.Assert.assertNotNull; import org.junit.Test; /** * * @author sunny */ public class TesMyBatis { @Test public void testMyBatis(){ SqlSession session = MyBatisUtils.getSession(); assertNotNull(session); if(session != null){ session.close(); } } }
时间: 2024-10-14 09:42:43