依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>dropwizard-project</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-hibernate</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
</dependencies>
</project>
注:
- dropwizard-hibernate依赖于dropwizard的其他包,所以导入dropwizard-hibernate就会导入其他
- 使用mysql,所以需要导入mysql-connector-java(实现了JDBC,为使用java开发的程序提供连接,方便java程序操作数据库)
配置
template: dw
server:
type: simple
database:
driverClass: com.mysql.cj.jdbc.Driver
user: root
password: root
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&autoReconnect=true&serverTimezone=Asia/Shanghai&useSSL=false
properties:
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto: update
hibernate.format_sql: true
hibernate.showSql: true
hibernate.current_session_context_class: thread
实体类
package com.jsq.hibernate.bean;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
@Entity
@Setter
@Getter
@ToString
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@Column
private int age;
@Column
private String email;
@Column
private String password;
}
配置类
package com.jsq.hibernate.config;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.dropwizard.Configuration;
import io.dropwizard.db.DataSourceFactory;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class HelloWorldConfiguration extends Configuration {
private String template;
private String defaultName = "Stranger";
private DataSourceFactory database = new DataSourceFactory();
@JsonProperty("database")
public DataSourceFactory getDataSourceFactory() {
return database;
}
}
DAO类(持久层,与数据库交互)
package com.jsq.hibernate.dao;
import com.jsq.hibernate.bean.Person;
import io.dropwizard.hibernate.AbstractDAO;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import java.util.ArrayList;
import java.util.List;
public class PersonDAO extends AbstractDAO<Person> {
private SessionFactory sessionFactory;
public PersonDAO(SessionFactory sessionFactory) {
super(sessionFactory);
this.sessionFactory = sessionFactory;
}
//需要事务
public List<Person> findAllPerson() {
Session session = this.sessionFactory.openSession();
List<Person> result = new ArrayList<>();
try {
Transaction transaction = session.beginTransaction();
StringBuilder sql = new StringBuilder().append("select e from ").append("com.jsq.hibernate.bean.Person").append(" e ");
System.out.println("sql is " + sql);
Query query = session.createQuery(sql.toString());
System.out.println(query.list().toArray().toString());
result.addAll((List<Person>) query.list());
transaction.commit();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public void create(Person person) {
Session session = this.sessionFactory.openSession();
try {
Transaction transaction = session.beginTransaction();
session.persist(person);
transaction.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
public Person findPersonById(Long id) {
Session session = this.sessionFactory.openSession();
try {
Transaction transaction = session.beginTransaction();
Query query = session.createQuery("from Person p where p.id = :id");
query.setParameter("id", id);
Person result = (Person) query.getSingleResult();
transaction.commit();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Resource 类
package com.jsq.hibernate.resource;
import com.codahale.metrics.annotation.Timed;
import com.jsq.hibernate.bean.Person;
import com.jsq.hibernate.dao.PersonDAO;
import org.hibernate.query.Query;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;
@Path("person")
@Produces(MediaType.APPLICATION_JSON)
public class PersonResource {
private PersonDAO personDAO;
public PersonResource(PersonDAO personDAO) {
this.personDAO = personDAO;
}
@GET
@Path("queryPerson")
@Timed
public List<Person> queryAllPerson() {
List<Person> person = personDAO.findAllPerson();
return person;
}
@POST
@Path("createPerson")
@Timed
public String createPersonDb(Person person) {
System.out.println(person.toString());
personDAO.create(person);
return "success";
}
@GET
@Path("queryPersonById")
@Timed
public Person queryPersonById(@QueryParam("id") Long id) {
System.out.println("id"+id);
Person person = personDAO.findPersonById(id);
return person;
}
}
启动类
package com.jsq.hibernate;
import com.jsq.hibernate.bean.Person;
import com.jsq.hibernate.config.HelloWorldConfiguration;
import com.jsq.hibernate.dao.PersonDAO;
import com.jsq.hibernate.resource.PersonResource;
import io.dropwizard.Application;
import io.dropwizard.db.PooledDataSourceFactory;
import io.dropwizard.hibernate.HibernateBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import java.net.URL;
import java.time.Period;
public class HelloWorldApplication extends Application<HelloWorldConfiguration> {
public static void main(String[] args) throws Exception {
URL yml = HelloWorldApplication.class.getClassLoader().getResource("server.yml");
String configFile = yml.getFile();
System.out.println(configFile);
args = new String[]{"server", configFile};
new HelloWorldApplication().run(args);
}
private static final Class[] classes = new Class[]{Person.class};
private final HibernateBundle<HelloWorldConfiguration> hibernate = new HibernateBundle<HelloWorldConfiguration>(Period.class,classes) {
@Override
public PooledDataSourceFactory getDataSourceFactory(HelloWorldConfiguration helloWorldConfiguration) {
return helloWorldConfiguration.getDataSourceFactory();
}
};
@Override
public void run(HelloWorldConfiguration helloWorldConfiguration, Environment environment) {
PersonDAO personDAO = new PersonDAO(hibernate.getSessionFactory());
environment.jersey().register(new PersonResource(personDAO));
}
@Override
public String getName() {
return "hello-world";
}
@Override
public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) {
bootstrap.addBundle(hibernate);
}
}
注
-
注册配置(将配置作为输入参数注入到启动类的线程中)
URL yml = HelloWorldApplication.class.getClassLoader().getResource("server.yml"); String configFile = yml.getFile(); args = new String[]{"server", configFile}; new HelloWorldApplication().run(args); -
注册hibernate
//与数据库中表对应的实体类 private static final Class[] classes = new Class[]{Person.class}; //新建HibernateBundle private final HibernateBundle<HelloWorldConfiguration> hibernate = new HibernateBundle<HelloWorldConfiguration>(Period.class,classes) { @Override public PooledDataSourceFactory getDataSourceFactory(HelloWorldConfiguration helloWorldConfiguration) { return helloWorldConfiguration.getDataSourceFactory(); } }; //初始化时启动类的添加hibernate @Override public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) { bootstrap.addBundle(hibernate); } -
jersey(web容器)中注册resource(定义restful api)
@Override public void run(HelloWorldConfiguration helloWorldConfiguration, Environment environment) { PersonDAO personDAO = new PersonDAO(hibernate.getSessionFactory()); environment.jersey().register(new PersonResource(personDAO)); }
本文介绍如何在Dropwizard项目中集成Hibernate,实现数据库操作。包括配置数据库连接、创建实体类、DAO类及RESTful API资源类,并展示了启动类的设置。

3311

被折叠的 条评论
为什么被折叠?



