Hibernate
//HibernateUtils.java import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; /** * @author Administrator * */ public class HibernateUtils { private static SessionFactory sessionFactory = null; static { try { sessionFactory = new AnnotationConfiguration().configure() .buildSessionFactory(); } catch (Exception e) { e.getStackTrace(); } } public static Session getSession() { return sessionFactory.openSession(); } public static void getClosed(Session session) { if (session != null) { session.close(); } } }
一般情况
//DbUtils.java import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * 连接数据库的公共类 * @author JSZX * */ public class DbUtils { private static Connection conn=null; static { try { Class.forName("com.mysql.jdbc.Driver"); try { conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1/mydatabase", "root", "root"); System.out.print(conn); } catch (SQLException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 获得连接信息 * @return */ public static Connection getConnection(){ return conn; } public static void closeConnection(){ if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
myBatis
//MyBatisUtils.java import java.io.IOException; 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; public class MyBatisUtils { private static SqlSessionFactory sqlSessionFactory=null; static { try { //配置连接数据库的资源文件 String resource="/com/cissst/mapping/mybatis-configuraction.xml"; //通过io流读取资源文件信息 InputStream inputStream =Resources.getResourceAsStream(resource); //通过SqlSessionFactoryBuilder创建SqlSessionFactory对象,同时传递io对象 sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } /** * 获得sqlSession对象该对象中有实例化接口的方法,同时SqlSession底层封装是jdbc信息,connection * @return */ public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
时间: 2024-10-19 03:14:47