在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>