Я пытаюсь вызвать проект гибернации, который возвращает некоторые результаты базы данных от AWS Lambda, я создаю функцию Lambda от пользователя IAM и пытаюсь указать базу данных mysql, которая размещена в моей учетной записи root из aws, из приложение. Теперь при тестировании функции я получаю
"errorMessage": "Неизвестная сущность: org.sample.serverless.aws.rds.Employee"
, что является ошибкой отображения в спящем режиме, но я не уверен, что является ее причиной
1.Это простая проблема конфигурации гибернации
2. Пользователь IAM не может получить доступ к RDS, размещенному в учетной записи root.
Я даю полную трассировку стека исключения и код, который я использую для приложения,
{
"errorMessage": "Unknown entity:
org.sample.serverless.aws.rds.Employee",
"errorType": "org.hibernate.MappingException",
"stackTrace": [
"org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:620)",
"org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1634)",
"org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)",
"org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)",
"org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)",
"org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)",
"org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)",
"org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)",
"org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:689)",
"org.hibernate.internal.SessionImpl.save(SessionImpl.java:681)",
"org.hibernate.internal.SessionImpl.save(SessionImpl.java:676)",
"org.sample.serverless.aws.rds.EmployeeHandler.handleRequest(EmployeeHandler.java:21)",
"org.sample.serverless.aws.rds.EmployeeHandler.handleRequest(EmployeeHandler.java:11)"
]
}
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>
<property name="connection.pool_size">1</property>
<mapping class="org.sample.serverless.aws.rds.Employee"></mapping>
</session-factory>
</hibernate-configuration>
Employee.java
package org.sample.serverless.aws.rds;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "employee")
public class Employee implements java.io.Serializable {
private int id;
private String name;
public Employee() {
}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Employee{" + "id=" + id + ", name=" + name + '}';
}
}
EmployeeHandler
public class EmployeeHandler implements RequestHandler<Request, String> {
@Override
public String handleRequest(Request request, Context context) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
try (Session session = sessionFactory.openSession()) {
session.beginTransaction();
Employee employee = new Employee();
employee.setId(request.id);
employee.setName(request.name);
session.save(employee);
session.getTransaction().commit();
}
return String.format("Added %s %s.", request.id, request.name);
}
}
HibernateUtil
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (null != sessionFactory)
return sessionFactory;
Configuration configuration = new Configuration();
String jdbcUrl = "jdbc:mysql://myrdsinstance.ciswboatdreq.us-east-1.rds.amazonaws.com/rdsTest";
configuration.setProperty("hibernate.connection.url", jdbcUrl);
configuration.setProperty("hibernate.connection.username", "rds");
configuration.setProperty("hibernate.connection.password", "Firewall#21");
configuration.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
try {
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (HibernateException e) {
System.err.println("Initial SessionFactory creation failed." + e);
throw new ExceptionInInitializerError(e);
}
return sessionFactory;
}
}
Запрос
public class Request {
int id;
String name;
public Request() {
}
public Request(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Request{" + "id=" + id + ", name=" + name + '}';
}
}
pom.xml
<?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.sample.serverless.aws</groupId>
<artifactId>employee</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-lambda-java-core -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-lambda -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-lambda</artifactId>
<version>1.11.569</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>${user.home}/.aws/credentials</file>
</files>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.bazaarvoice.maven.plugins</groupId>
<artifactId>s3-upload-maven-plugin</artifactId>
<version>1.4</version>
<configuration>
<accessKey>${aws_access_key_id}</accessKey>
<secretKey>${aws_secret_access_key}</secretKey>
<bucketName>hr-s3-bucket</bucketName>
<source>target/${project.artifactId}-${project.version}.jar</source>
<destination>${project.artifactId}-${project.version}.jar</destination>
</configuration>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>s3-upload</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>