在IntelliJ IDEA中配置MySQL Database.

Database是我们事先建立的数据库,对应我们的某一个项目.

添加Hibernate框架.

项目上右键->Add Framework Support.

Package是放置我们的实体类,一般是xx.xx.model就可以了.

生成的实体类已经包含了映射信息,所以不需要x.hbm.xml文件了.

@Entity
@Table(name = "users", schema = "mydb", catalog = "")
public class UsersEntity {
    private int id;
    private String name;
    private Byte age;

    @Id
    @Column(name = "id", nullable = false)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Basic
    @Column(name = "name", nullable = true, length = 100)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Basic
    @Column(name = "age", nullable = true)
    public Byte getAge() {
        return age;
    }

    public void setAge(Byte age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        UsersEntity that = (UsersEntity) o;

        if (id != that.id) return false;
        if (name != null ? !name.equals(that.name) : that.name != null) return false;
        if (age != null ? !age.equals(that.age) : that.age != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (age != null ? age.hashCode() : 0);
        return result;
    }
}

那么再来看看Hiebrnate的配置文件,注意,该配置文件不在正确的路径上。在WEB-INF下建立文件夹classes,放进去.

没有Driver的jar包.

拷贝到lib目录中,还没完,为什么呢?没有添加到Build Path中.看!前面都没有三角标记.

跟别人不一样嘛.

右键项目->Open Model Settings->Libraries.

要注意关注Problems.

系统为我们生成了数据库连接的代码

public class Main {
    private static final SessionFactory ourSessionFactory;
    private static final ServiceRegistry serviceRegistry;

    static {
        try {
            Configuration configuration = new Configuration();
            configuration.configure();

            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            ourSessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() throws HibernateException {
        return ourSessionFactory.openSession();
    }

    public static void main(final String[] args) throws Exception {
        final Session session = getSession();
        try {
            System.out.println("querying all the managed entities...");
            final Map metadataMap = session.getSessionFactory().getAllClassMetadata();
            for (Object key : metadataMap.keySet()) {
                final ClassMetadata classMetadata = (ClassMetadata) metadataMap.get(key);
                final String entityName = classMetadata.getEntityName();
                final Query query = session.createQuery("from " + entityName);
                System.out.println("executing: " + query.getQueryString());
                for (Object o : query.list()) {
                    System.out.println("  " + o);
                }
            }
        } finally {
            session.close();
        }
    }
}

新建目录db,将Main类改名成DbConnections.

获取数据库中的数据

@Controller
@RequestMapping("/users")
public class UserController {

    @RequestMapping(value = "/list.do", method = RequestMethod.GET)
    public String listUsers(ModelMap map) {
        Session session = DbConnections.getSession();
        List<UsersEntity> list = session.createCriteria(UsersEntity.class).list();
        map.addAttribute("users", list);
        session.close();
        return "users";
    }
}

doc + Alt + /:生成html模板,Alt + /需要自己配置.

<%@ page import="com.winner.db.entities.UsersEntity" %>
<%@ page import="java.util.List" %>
<%@ page pageEncoding="utf-8" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<ol>
    <%for (UsersEntity e:(List<UsersEntity>)request.getAttribute("users")){%>
        <li>名字:<%out.println(e.getName());%>,年龄:<%out.println(e.getAge());%></li>
    <%}%>
</ol>
</body>
</html>

向数据库中添加用户:

@Controller
@RequestMapping("/users")
public class UserController {

    @RequestMapping(value = "/list.do", method = RequestMethod.GET)
    public String listUsers(ModelMap map) {
        Session session = DbConnections.getSession();
        List<UsersEntity> list = session.createCriteria(UsersEntity.class).addOrder(Order.desc("id")).list();
        map.addAttribute("users", list);
        session.close();
        return "users";
    }

    @RequestMapping(value = "/add.do", method = RequestMethod.GET)
    public String addUser() {
        return "add_user";
    }

    @RequestMapping(value = "/result.do", method = RequestMethod.GET)
    public String result(ModelMap map, String name, int age) {
        map.addAttribute("name", name);
        map.addAttribute("age", age);
        Session session = DbConnections.getSession();
        Transaction transaction = session.beginTransaction();
        UsersEntity ue = new UsersEntity();
        ue.setName(name);
        ue.setAge((byte) age);
        session.save(ue);
        transaction.commit();
        session.close();
        return "redirect:list.do";
    }
}
<%@ page pageEncoding="utf-8" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <form action="/users/result.do" method="get" >
        名字:<input type="text" name="name"/>
        年龄:<input type="text" name="age">
        <input type="submit" value="submit"/>
    </form>
</body>
</html>

*IntelliJ IDEA使用Hibernate连接数据库的更多相关文章

  1. Intellij IDEA的Hibernate简单应用

    1.创建数据库及其表 create database demo;    use demo; CREATE TABLE `user` (   `id` int(10) unsigned NOT NULL ...

  2. 【转载】Intellij IDEA的Hibernate简单应用

    转载自: https://www.cnblogs.com/yangyquin/p/5438248.html   1.创建数据库及其表 create database demo;    use demo ...

  3. *IntelliJ IDEA配置Hibernate

    为IntelliJ IDEA安装Hibernate插件

  4. JDBC、mybatis、hibernate连接数据库

    JDBC连接数据库五步骤: 一.加载驱动 Class.forName(“com.mysql.jdbc.Driver”); 二.建立连接 Connection conn = DriverManager. ...

  5. 【笔记】IntelliJ IDEA配置Hibernate

    参考:imooc:http://www.imooc.com/video/7706 1.创建Hibernate的配置文件. 将依赖包导入项目.http://blog.csdn.net/a15337525 ...

  6. MySQL数据库的使用流程,代码解释+Hibernate连接数据库

    数据库的使用流程: 1.注册驱动: 2.用DriverManager.getConnection方法获得连接对象con: A方法:  3.用连接对象的createStatement()方法,获得可以执 ...

  7. hibernate连接数据库和反向工程

    一.JSP界面连接数据库: 导包:将11个包倒进web-inf的lib目录下: 二.建立hibernate.cfg.xml的配置文件:!注意:是放到项目SRC目录下: 三.将视图切换到java下,在左 ...

  8. hibernate连接数据库和使用

    hibernate.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibe ...

  9. Hibernate连接数据库

    包结构如下图所示(按图标进行对齐): 环境搭好后代码分为以下几步: /** * private static final Configuration CONFIGURATION; * private ...

随机推荐

  1. How to: Create Your Own Test Certificate (.pfx)

    Original MSDN Link: https://msdn.microsoft.com/en-us/library/ff699202.aspx

  2. 查看Aix系统配置命令

    prtconf#topas http://baike.baidu.com/link?url=QruEnlfCqyoqQ565LicyKxIGMQYSkVesj6j9GzHWwzpDOagXtuprhT ...

  3. 分享我写的IOCP:源码+思路

    首先说明,下面的代码仅是一个IOCP的demo,很多地方的设计非常差,当然也有一些设计还算可以:).此篇仅供对IOCP有些了解但又不深入的.需要一个稍微完整示例的.对网络编程感兴趣的同学参考.点击这里 ...

  4. 鼠标按键自定义软件-X-Mouse Button Control

    转载说明 本篇文章可能已经更新,最新文章请转:http://www.sollyu.com/mouse-button-x-mouse-button-custom-software-control/ 说明 ...

  5. Maven Dependency Scope用法

    原帖地址:http://uule.iteye.com/blog/2087485 官方API描述 Dependency scope 是用来限制Dependency的作用范围的, 影响maven项目在各个 ...

  6. 【CLR VIA C#】读书笔记

    工作几年了才看,记录下笔记备忘. 章节 笔记 1.CLR的执行模型 公共语言运行时(Common Language Runtime,CLR) 源代码-->编译器检查语法和分析源代码-->托 ...

  7. 一款js点击显示和隐藏的例子(pc,移动端通用)

    html部分: <div id="box"> <div id="box_title">标题</div> <div id ...

  8. ECSHOP如何解决购物车中商品自动消失问题

    最近有客户反映关于ECShop购物车的问题:需要加入多个商品到购物车时,发现之前加入到购物车的商品都自动消失了,只有最后一次加入购物车的商品在里面.那么,这是什么原因呢? 因为ECShop的SESSI ...

  9. Centos7搭建集中式日志系统

    在CentOS7中,Rsyslong是一个集中式的日志收集系统,可以运行在TCP或者UDP的514端口上.   目录 开始之前 配置接收日志的主机 配置发送日志的主机 日志回滚 附件:创建日志接收模板 ...

  10. Python问题之奇怪诡异的Bug

    最近又重新装上了windows 7感觉还是那样,主要是想用M8SDK写些程序.也想在windows上玩玩,一直都觉得用C写一些常用的东东很复杂,只有借助于解释性语言了,在python, ruby间选择 ...