版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_39819880/article/details/81434000
文章简介
做java开发快一年,认为学习框架还是从最基本的学习,才能融汇贯通。做个笔记,mark一下。。。
项目和数据库结构(jar包去Maven仓库下载)
Role实体类(Role.java)
package org.lbl.conn.pojo;
/**
* @description:
* @author: libl
* @date: 2018年8月2日 下午5:09:33
*/
public class Role {
private Long id;
private String roleName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
private String note;
}
1.JDBC连接
1.JDBC例子(JdbcExample .java)
package org.lbl.conn.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.lbl.conn.pojo.Role;
/**
* @description:JDBC连接数据库实现查询一个角色编号为1的角色名称。
* @author: libl
* @date: 2018年8月2日 下午4:44:09
*/
public class JdbcExample {
private Connection getConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/db_role";
String user = "root";
String password = "root";
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(JdbcExample.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
return connection;
}
public Role getRole(Long id) {
Connection connection = getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = connection.prepareStatement("select id, role_name, note from t_role where id=?");
ps.setLong(1, id);
rs = ps.executeQuery();
while (rs.next()) {
Long roleId = rs.getLong("id");
String userName = rs.getString("role_name");
String note = rs.getString("note");
Role role = new Role();
role.setId(roleId);
role.setRoleName(userName);
role.setNote(note);
return role;
}
} catch (SQLException ex) {
Logger.getLogger(JdbcExample.class.getName()).log(Level.SEVERE, null, ex);
} finally {
this.close(rs, ps, connection);
}
return null;
}
private void close(ResultSet rs, Statement stmt, Connection connection) {
try {
if (rs != null && rs.isClosed()) {
rs.close();
}
} catch (SQLException ex) {
Logger.getLogger(JdbcExample.class.getName()).log(Level.SEVERE, null, ex);
}
try {
if (stmt != null && !stmt.isClosed()) {
stmt.isClosed();
}
} catch (SQLException ex) {
Logger.getLogger(JdbcExample.class.getName()).log(Level.SEVERE, null, ex);
}
try {
if (connection != null && connection.isClosed()) {
connection.isClosed();
}
} catch (SQLException ex) {
Logger.getLogger(JdbcExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
JdbcExample example = new JdbcExample();
Role role = example.getRole(1L);
System.err.println("role_name => " + role.getRoleName());
}
}
2.Hibernate连接
1. Hibernate配置文件(hibernate.cfg.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/db_role</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="org/lbl/conn/pojo/TRole.hbm.xml" />
</session-factory>
</hibernate-configuration>
2.Hibernate实体类映射(TRole.hbm.xml)
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2018-8-2 18:07:22 by Hibernate Tools 3.5.0.Final -->
<!-- 描述POJO和数据库表的映射关系,Hibernate通过配置文件(或注解)就可以把数据库的数据直接映射到POJO上,可以通过操作POJO去操作数据库记录 -->
<hibernate-mapping>
<class name="org.lbl.conn.pojo.Role" table="T_ROLE">
<id name="id" type="java.lang.Long">
<column name="ID" />
<generator class="assigned" />
</id>
<property name="roleName" type="java.lang.String">
<column name="ROLE_NAME" />
</property>
<property name="note" type="java.lang.String">
<column name="NOTE" />
</property>
</class>
</hibernate-mapping>
3.Hibernate工具类(HibernateUtil .java)
package org.lbl.conn.hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* @description:Hibernate工厂对象,用它来做全局对象,产生Session接口,就可以操作数据库了。
* @author: libl
* @date: 2018年8月2日 下午6:13:22
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
Configuration cfg = new Configuration().configure("/org/lbl/conn/hibernate/hibernate.cfg.xml");
sessionFactory = cfg.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
4.Hibernate例子(HibernateExample.java )
package org.lbl.conn.hibernate;
import org.hibernate.Session;
import org.lbl.conn.pojo.Role;
/**
* @description:对比JDBC好处: 1.消除了代码的映射规则,它全部被分离到了XML或者注解里面去配置
* 2.无需再管理数据库连接,它也配置在XML里面
* 3.一个会话中,不要操作多个对象,只要操作Session对象即可
* 4.关闭资源只需要关闭一个Session便可
* @author: libl
* @date: 2018年8月3日 上午9:08:12
*/
public class HibernateExample {
public static void main(String[] args) {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
Role role = (Role) session.get(Role.class, 1L);
System.out.println("role_name => " + role.getRoleName());
} finally {
if (session != null) {
session.close();
}
}
}
}
3. Mybatis连接
1.Mybatis配置文件(mybatis_config.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>
<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/db_role" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="RoleMapper.xml" />
</mappers>
</configuration>
2.Mybatis工具类(MybatisUtil.java)
package org.lbl.conn.mybatis;
import java.io.IOException;
import java.io.InputStream;
import javax.annotation.Resource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
* @description:
* @author: libl
* @date: 2018年8月3日 上午11:04:27
*/
public class MybatisUtil {
private static SqlSessionFactory sqlSessionFactory = null;
public static SqlSessionFactory getSqlSessionFactory() {
if (sqlSessionFactory == null) {
try {
String resource = "mybatis_config.xml";
sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(resource));
return sqlSessionFactory;
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
return sqlSessionFactory;
}
}
3.Mybatis映射类(RoleMapper .java)
package org.lbl.conn.mybatis;
import org.lbl.conn.pojo.Role;
/**
* @description:
* @author: libl
* @date: 2018年8月3日 上午11:03:23
*/
public interface RoleMapper {
public Role getRole(Long id);
}
4. Mybatis映射文件(RoleMapper.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="org.lbl.conn.mybatis.RoleMapper">
<select id="getRole" parameterType="long" resultType="org.lbl.conn.pojo.Role">
select
id,role_name as roleName, note from t_role where id=#{id}
</select>
</mapper>
5.. Mybatis例子(MyBatisExample .java)
package org.lbl.conn.mybatis;
import org.apache.ibatis.session.SqlSession;
import org.lbl.conn.pojo.Role;
/**
* @description:
* @author: libl
* @date: 2018年8月3日 上午11:11:28
*/
public class MyBatisExample {
public static void main(String[] args) {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtil.getSqlSessionFactory().openSession();
RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
Role role = roleMapper.getRole(1L);
System.out.println("role_name =>" + role.getRoleName());
} finally {
sqlSession.close();
}
}
}
6. 日志文件(log4j.properties)
log4j.rootLogger=DEBUG, stdout
# SqlMap logging configuration...
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.cache.CacheModel=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientImpl=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.builder.xml.SqlMapParser=DEBUG
log4j.logger.com.ibatis.common.util.StopWatch=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n