用JavaSE简单入门MyBatis连接MySQL…
来源:互联网 发布:淘宝怎么做数据分析 编辑:程序博客网 时间:2024/05/17 01:19
在Netbeans中新建一个 Java——Java应用程序 项目,其目录结构如下:
STUDENT_ID VARCHAR(255) PRIMARYKEY, STUDENT_NAME VARCHAR(10) NOTNULL, STUDENT_SEX VARCHAR(10), STUDENT_BIRTHDAY DATE, CLASS_ID VARCHAR(255)
STUDENT_NAME, STUDENT_SEX, STUDENT_BIRTHDAY, CLASS_ID) VALUES (123456, '某某某', '女', '1980-08-01', 121546 )
// Setter…… …… …… …… public void println(){ System.out.print(this.studentID+" "); System.out.print(this.studentName+" "); System.out.print(this.studentSex+" "); System.out.println(this.studentBirthday); }
@Override public StudentEntity getStudent(StringstudentID) { } ……………………
需要准备和下载的jar库:
1、mybatis-3.4.1.jar
2、mysql-connector-java-5.1.39-bin.jar(安装MySQL的时候,勾选安装Connector.J后会附带有,在MySQL 安装目录/Connector.J 5.1 里面)
添加好库后,就可以开始干活了。
首先得在MySQL里面建立数据库和表格:
文件student.sql——不过这个文件并不参与MyBatis。我单独登录MySQLClient然后在命令行输入SQL语句创建的表格
CREATE DATABASESTUDENT_MANAGER;
USESTUDENT_MANAGER;
CREATE TABLESTUDENT_TBL
(
);
INSERT INTO STUDENT_TBL(STUDENT_ID,
创建完后数据库里面的内容,用MySQL Workbench查看:
然后我们开始编写类:
首先,我们把这个STUDENT_TBL表的表头编写成一个POJO类(只含有成员变量,setter和getter的简单Java对象“PlainOrdinary Java Object”)
文件StudentEntity.Java
packagemybatishelloworld;
importjava.io.Serializable;
importjava.util.Date;
public class StudentEntityimplements Serializable {private static final longserialVersionUID = 3096154202413606831L;
private DatestudentBirthday;
private StringstudentID;
private StringstudentName;
private StringstudentSex;
public DategetStudentBirthday() {
returnstudentBirthday;
}
public String getStudentID(){
return studentID;
}
public String getStudentName(){
returnstudentName;
}
public String getStudentSex(){
return studentSex;
}
public voidsetStudentBirthday(Date studentBirthday) {
this.studentBirthday =studentBirthday;
}
public void setStudentID(StringstudentID) {
this.studentID =studentID;
}
public voidsetStudentName(String studentName) {
this.studentName =studentName;
}
public voidsetStudentSex(String studentSex) {
this.studentSex =studentSex;
}
}
其实为了方便演示,这个Java类并不纯粹,而是添加了个println方法便于打印SQL后的结果
接着我们建立一个Mapper接口——于是,我们为什么需要一个映射(Mapper)接口呢?
原因我们看看代码就懂了:
文件StudentMapper.java
package mybatishelloworld;
import java.util.List;
public interface StudentMapper {
import java.util.List;
public interface StudentMapper {
public StudentEntitygetStudent(String studentID);
public StudentEntitygetStudentAndClass(String studentID);
public List getStudentAll();
public voidinsertStudent(StudentEntity entity);
public voiddeleteStudent(StudentEntity entity);
public voidupdateStudent(StudentEntity entity);
}
我们发现,这个接口里面都是方法名。按照常规的Java思维,要真正用接口,必须有方法的实现才行:
public class StudentMapperImplimplements StudentMapper{
StudentEntityse=SQL.get(studentID); //那个头疼啊,还像JDBC一样把SQL语句写到字符串里面?
}
但是!但是的但是!这个具体的实现,在Mybatis里面,不需要我们写Java了。你可以把怎么用SQL语句get这个StudentEntity,写到一个xml文件里面。所以,这个接口Interface,就是用来映射XML文件里面的SQL查询语句的,如何把xml里的sql转换为java语句里的jdbc,交由MyBatis来完成。下面就是与之相对应的XML文件:
文件StudentMapper.xml
<?xmlversion="1.0"encoding="UTF-8"?> <!-- Student类的sql语句文件StudentMapper.xml resultMap标签:表字段与属性的映射。 Select标签:查询sql。 由于StudentEntity已经在mybatis-config.xml里面 映射成了mybatishelloworld.StudentEntity,即 mybatishelloworld目录下的StudentEntity.java类 所以这里的type后面直接跟着StudentEntity,MyBatis就知道如何寻找使用 StudentEntity类了。 -->
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mappernamespace="mybatishelloworld.StudentMapper">
<resultMaptype="StudentEntity"id="studentResultMap">
<idproperty="studentID"column="STUDENT_ID"/>
<resultproperty="studentName"column="STUDENT_NAME"/>
<resultproperty="studentSex"column="STUDENT_SEX"/>
<resultproperty="studentBirthday"column="STUDENT_BIRTHDAY"/>
</resultMap>
<!-- 查询学生,根据id-->
<selectid="getStudent"parameterType="String"resultType="StudentEntity"resultMap="studentResultMap">
<![CDATA[
SELECT * from STUDENT_TBLST
WHERE ST.STUDENT_ID =#{studentID}
]]>
</select>
<!-- 查询学生列表-->
<selectid="getStudentAll" resultType="StudentEntity"resultMap="studentResultMap">
<![CDATA[
SELECT * fromSTUDENT_TBL
]]>
</select>
</mapper>
为了使用Mybatis,我们还得个它一个配置文件,配置所使用的数据库类型,数据库连接地址,用户名和密码等等,这个文件的配置如下:
文件mybatis-config.xml
<?xmlversion="1.0"encoding="UTF-8"?> PUBLIC"-//mybatis.org//DTD Config3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!-- typeAliases这玩意儿一定要放在environment的开头,可以参照报错的顺序设置: 顺序同错误提示信息一致: 元素类型为"configuration" 的内容必须匹配"(properties?,settings?, typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?, reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?) —————byhttp://blog.csdn.net/liu578182160/article/details/50747390 --> <typeAliases> <typeAliasalias="StudentEntity"type="mybatishelloworld.StudentEntity"/> </typeAliases> <environmentsdefault="development"> <environmentid="development"> <transactionManagertype="JDBC"/> <dataSourcetype="POOLED"> <propertyname="driver"value="com.mysql.jdbc.Driver"/> <propertyname="url"value="jdbc:mysql://localhost:3306/student_manager?useSSL=true"/> <propertyname="username"value="root"/> <propertyname="password"value="rootOfPasswd"/> </dataSource> </environment> </environments> <!-- 创建MyBatis的mapper配置文件 创建MyBatis配置文件:mybatis-config.xml。 Mappers标签:加载MyBatis中实体类的SQL映射语句文件。 --> <mappers> <mapperresource="mybatishelloworld/StudentMapper.xml"/> </mappers>
<!DOCTYPEconfiguration
<configuration>
</configuration>
数据库驱动跟Hibernate里面一样,连接MySQL的话,用的是value=com.mysql.jdbc.Driver
最后我们在MainClass的main函数里面,测试我们的整个配置
文件MainClass.java
packagemybatishelloworld;
public static void main(String[] args){ Stringresource = "mybatishelloworld/mybatis-config.xml"; //告诉MyBatis核心配置文件在哪里 InputStream inputStream = null; try{ inputStream =Resources.getResourceAsStream(resource); }catch(IOExceptionex){Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE,null, ex);}
//打开SQL对话工厂 SqlSessionFactory sqlSessionFactory = newSqlSessionFactoryBuilder().build(inputStream); try(SqlSession session = sqlSessionFactory.openSession()) { //用工厂生成一个对话 //这里是精华,session用getMapper方法从xml里面生成了StudentMapper接口的实现类 StudentMapper mapper =(StudentMapper)session.getMapper(StudentMapper.class); StudentEntity se =mapper.getStudent("123456"); //于是这个类就有了具体的getStudent方法 se.println(); Listlist=mapper.getStudentAll(); list.forEach((s)->{ s.println(); }); } }//End-Of-Main
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.List;
importjava.util.logging.Level;
importjava.util.logging.Logger;
importorg.apache.ibatis.io.Resources;
importorg.apache.ibatis.session.SqlSession;
importorg.apache.ibatis.session.SqlSessionFactory;
importorg.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MainClass{
}
在Netbeans编译运行后的结果:
0 0
- 用JavaSE简单入门MyBatis连接MySQL…
- javase简单入门1
- javase简单入门4 数组
- Mybatis连接MySQL或者ORALE 12C 入门实例。
- mybatis连接mysql
- MyBatis连接MySql
- mybatis连接MySQL超时
- Java:MyBatis简单入门
- myBatis简单入门
- Mybatis简单入门
- 一、MyBatis简单入门
- Mybatis简单入门
- Mybatis简单入门
- mybatis简单入门
- MyBatis简单入门使用
- MyBatis简单入门使用
- MyBatis框架简单入门
- mybatis简单入门实例
- (二)详细代码教程——成功在Netbea…
- Git 与 GitHub 使用
- Git 连接 GitHub
- 单元测试Netbeans 出现 …
- Hexo+Github 博客搭建
- 用JavaSE简单入门MyBatis连接MySQL…
- iOS开发之再探多线程编程:Grand Central Dispatch详解
- hive hql 语句
- MyBatis与Hibernate图文对比
- org.hibernate.hql.internal.ast.Q…
- Linux中shell编程需要避免的坑之shell语法篇(一)
- Fragment中startActivityForResult,并在Fragment中接收返回结果
- MyBatis与Hibernate更改schema的方…
- Spring中AOP,一个query与check的…