主要搭建过程
1. pom.xml文件中加入mybatis和数据库依赖,这里使用mysql:
<properties> <mybatis.version>3.2.3</mybatis.version> <mysql.version>5.1.26</mysql.version> <slf4j.api.version>1.7.5</slf4j.api.version> <testng.version>6.8.7</testng.version> </properties> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- Database driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- mybatis启动要加载log4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.api.version}</version> </dependency> <!-- Test --> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>${testng.version}</version> </dependency> </dependencies>
2. 在类路径下创建mybatis的配置文件Configuration.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> <typeAliases><!-- 别名 --> <typeAlias alias="User" type="com.john.hbatis.model.User" /> </typeAliases> <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/hbatis" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <mappers><!-- ORM映射文件 --> <mapper resource="com/john/hbatis/model/User.xml" /> </mappers> </configuration>
3. 执行创建数据库和表的sql:
-- Create the database named 'hbatis'. -- It's OK to use `, not OK to use ' or " surrounding the database name to prevent it from being interpreted as a keyword if possible. CREATE DATABASE IF NOT EXISTS `hbatis` DEFAULT CHARACTER SET = `UTF8`; -- Create a table named 'User' CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) DEFAULT NULL, `age` int(11) DEFAULT NULL, `address` varchar(200) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- Insert a test record Insert INTO `user` VALUES ('1', 'john', '120', 'hangzhou,westlake');
4. com.john.hbatis.model.User类:
public class User { private int id; private String name; private String age; private String address; // Getters and setters are omitted // 如果有带参数的构造器,编译器不会自动生成无参构造器。当查询需要返回对象时,ORM框架用反射来调用对象的无参构造函数,导致异常:java.lang.NoSuchMethodException: com.john.hbatis.model.User.<init>() // 这时需要明确写出: public User() { } public User(int id, String address) { this.id = id; this.address = address; } public User(String name, int age, String address) { this.name = name; this.age = age; this.address = address; } }
com/john/hbatis/model路径下的User.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="com.john.hbatis.model.UserMapper"> <select id="getUserById" parameterType="int" resultType="User"> select * from `user` where id = #{id} </select> </mapper>
5. 测试类:
public class MyBatisBasicTest { private static final Logger log = LoggerFactory.getLogger(MyBatisBasicTest.class); private static SqlSessionFactory sqlSessionFactory; private static Reader reader; @BeforeClass public static void initial() { try { reader = Resources.getResourceAsReader("Configuration.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { log.error("Error thrown while reading the configuration: {}", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { log.error("Error thrown while closing the reader: {}", e); } } } } @Test public void queryTest() { SqlSession session = sqlSessionFactory.openSession(); User user = (User)session.selectOne("com.john.hbatis.model.UserMapper.getUserById", 1); log.info("{}: {}", user.getName(), user.getAddress()); } }
以接口方式交互数据
上面的环境搭建是采用SqlSession的通用方法并强制转换的方式,存在着转换安全的问题:
User user = (User)session.selectOne("com.john.hbatis.model.UserMapper.getUserById", 1);
可以采用接口加sql语句的方式来解决,sql语句理解为是接口的实现:
1. 新建接口类:
package com.john.hbatis.mapper; import com.john.hbatis.model.User; public interface IUserMapper { User getUserById(int id); }
2. 修改User.xml文件,确保namespace属性值和接口的全限定名相同,且id属性值和接口方法名相同:
<mapper namespace="com.john.hbatis.mapper.IUserMapper"> <select id="getUserById"
3. 在MyBatisBasicTest类中添加测试方法:
@Test public void queryInInterfaceWayTest() { SqlSession session = sqlSessionFactory.openSession(); IUserMapper mapper = session.getMapper(IUserMapper.class); // 如果namespace和接口全限定名不一致,报org.apache.ibatis.binding.BindingException: Type interface com..IUserMapper is not known to the MapperRegistry异常。 User user = mapper.getUserById(1); log.info("{}: {}", user.getName(), user.getAddress()); }
附:
上面的实现是把sql语句放在XML文件中,并通过一定的约束来保证接口能够在XML中找到对应的SQL语句;
还有一种方式是通过接口+注解SQL方式来交互数据:
1. 新建接口类:
package com.john.hbatis.mapper; import org.apache.ibatis.annotations.Select; import com.john.hbatis.model.User; public interface IUserMapper2 { @Select({ "select * from `user` where id = #{id}" }) User getUserById(int id); }
2. 在Configuration.xml文件中加入:
<mappers> <mapper class="com.john.hbatis.mapper.IUserMapper2" /> </mappers>
或在初始化语句中加入:
sqlSessionFactory.getConfiguration().addMapper(IUserMapper2.class);
3. 相应修改上面的测试方法:
IUserMapper2 mapper = session.getMapper(IUserMapper2.class);
本文向大家介绍Windows下Java+MyBatis框架+MySQL的开发环境搭建教程,包括了Windows下Java+MyBatis框架+MySQL的开发环境搭建教程的使用技巧和注意事项,需要的朋友参考一下 MyBatis是一个Java持久化框架,它通过XML描述符或注解把对象与存储过程或SQL语句关联起来。 MyBatis是在Apache许可证 2.0下分发的自由软件,是iBATIS 3.0
本文向大家介绍JAVA开发环境搭建教程,包括了JAVA开发环境搭建教程的使用技巧和注意事项,需要的朋友参考一下 一、安装JDK 1、 JVM(Java Virtual Machine—Java虚拟机) JRE(Java Runtime Environment—Java运行时环境) JDK(Java Development kit—Java开发工具包) 2、JDK包含了JRE和JVM,所以安装了JD
目标 下载和安装 JDK 和 Eclipse IDE 设置 Eclipse 开发环境 了解主要的 Eclipse 组件和如何使用它们执行 Java 开发 在 Eclipse 中创建新 Java 项目 您的开发环境 JDK 包含一组用于编译和运行 Java 代码的命令行工具,其中包括 JRE 的一个完整副本。尽管可以使用这些工具开发应用程序,但除了任务管理和可视界面外,IDE 还提供了额外的功能。
依照以下操作,你可使用Docker在Mac,Linux上搭建PPMessage开发环境。 前言:Docker 的作用 ? Docker allows you to package an application with all of its dependencies into a standardized unit for software development. Docker containe
本文向大家介绍Python3开发环境搭建详细教程,包括了Python3开发环境搭建详细教程的使用技巧和注意事项,需要的朋友参考一下 Python 环境安装 下载 Python 安装包 进入 python 官网 ,在Downloads(下载)下面,点击 Window 进入下载列表页 这里我们看到两个大类: Stable Releases 稳定版本:经过测试和使用迭代,bug较少。可用于工作学习 Pr
本文向大家介绍Android Studio开发环境搭建教程详解,包括了Android Studio开发环境搭建教程详解的使用技巧和注意事项,需要的朋友参考一下 对于移动端这块,笔者之前一直都是进行iOS开发的,也从来没用过Java。但是因为进入了Google Android全国大学生移动互联网创新挑战赛(进入官网)的总决赛(笔者“西部计算机教育提升计划”的项目被直接推荐进入决赛),这个比赛要求一定
要开发kibana 插件,首先要在本地搭建开发环境,我这里推荐使用vs code,如果问我为什么,我只想说这么火的开发工具,不用一下,怎么跟上世界开发潮流呢。 第一步 首先 需要安装node.js,可以去官网下载最新版本,对于如何安装就不废话了。 第二步 下载 kibana 源代码,在github下载即可。 第三步 在kibana项目根目录下执行 1. $ git tag 2. $ git che
简单起见,一开始的服务器只会是一个工程,构建会也只是一个jar包。 开发环境就用最流行的java8、maven3,IDE可以随自己喜好。 新建maven工程,如下: POM文件如下: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi