做java开发快一年,认为学习框架还是从最基本的学习,才能融汇贯通。做个笔记,mark一下。。。
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;
}
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());
}
}
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driverproperty>
<property name="hibernate.connection.password">rootproperty>
<property name="hibernate.connection.url">jdbc:mysql://localhost/db_roleproperty>
<property name="hibernate.connection.username">rootproperty>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialectproperty>
<mapping resource="org/lbl/conn/pojo/TRole.hbm.xml" />
session-factory>
hibernate-configuration>
<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>
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;
}
}
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();
}
}
}
}
<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>
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;
}
}
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);
}
<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>
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();
}
}
}
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