Я пытаюсь написать тест на сохранение. У меня есть проект Maven, и я использую Arquillian со встроенным контейнером из стеклянной рыбы, Hibernate (как мой поставщик JPA) и HSQLDB в качестве моего магазина.Исключение грамматики спящего режима с использованием JPA с hsqldb
Когда я запускаю мой тест я получаю исключение грамматики (я могу опубликовать полный трассировки стека, если необходимо:
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: Syntax error: Encountered "identity" at line 1, column 6.
Бревна, кажется, чтобы показать таблицу создана правильно:
Hibernate:
create table Game (
id bigint generated by default as identity (start with 1),
title varchar(50) not null,
primary key (id)
)
Dumping old records...
Hibernate:
delete
from
Game
Inserting records...
Hibernate:
insert
into
Game
(id, title)
values
(default, ?)
Hibernate:
drop table Game if exists
Hibernate:
drop table Member if exists
I «ве включено то, что я думаю, соответствующие файлы
- persistence.xml
- pom.xml
- Entity класса
- Тест класс
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="testPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>Member</class>
<class>Game</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:demodb" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
pom.xml
<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>....</groupId>
<artifactId>....</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>Web App</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<netbeans.hint.deploy.server>gfv3ee6</netbeans.hint.deploy.server>
<arquillian.version>1.0.0.Alpha2</arquillian.version>
</properties>
<dependencies>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.2.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.1.9.Final</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.arquillian</groupId>
<artifactId>arquillian-bom</artifactId>
<version>1.0.3.Final</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<profiles>
<profile>
<id>arquillian-glassfish-embedded</id>
<dependencies>
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-glassfish-embedded-3.1</artifactId>
<version>1.0.0.CR3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<version>3.1.2</version>
<scope>provided</scope>
</dependency>
</dependencies>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.13</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>6.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<finalName>....</finalName>
</build>
<repositories>
<repository>
<url>http://download.java.net/maven/2/</url>
<id>hibernate-support</id>
<layout>default</layout>
<name>Repository for library Library[hibernate-support]</name>
</repository>
<repository>
<url>http://ftp.ing.umu.se/mirror/eclipse/rt/eclipselink/maven.repo</url>
<id>eclipselink</id>
<layout>default</layout>
<name>Repository for library Library[eclipselink]</name>
</repository>
</repositories>
</project>
Entity
//imports removed
@Entity
public class Game implements Serializable {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
public Game() {}
public Game(String title) {
this.title = title;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@NotNull
@Size(min = 3, max = 50)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "[email protected]" + hashCode() + "[id = " + id + "; title = " + title + "]";
}
}
* Тест класс
//imports removed
@RunWith(Arquillian.class)
public class GamePersistenceTest {
@Deployment
public static Archive<?> createDeployment() {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addPackage(Game.class.getPackage())
.addAsResource("META-INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
private static final String[] GAME_TITLES = {
"Super Mario Brothers",
"Mario Kart",
"F-Zero"
};
@PersistenceContext
EntityManager em;
@Inject
UserTransaction utx;
// tests go here
@Test
public void shouldFindAllGamesUsingJpqlQuery() throws Exception {
// given
String fetchingAllGamesInJpql = "select g from Game g order by g.id";
// when
System.out.println("Selecting (using JPQL)...");
List<Game> games = em.createQuery(fetchingAllGamesInJpql, Game.class).getResultList();
// then
System.out.println("Found " + games.size() + " games (using JPQL):");
assertContainsAllGames(games);
}
private static void assertContainsAllGames(Collection<Game> retrievedGames) {
Assert.assertEquals(GAME_TITLES.length, retrievedGames.size());
final Set<String> retrievedGameTitles = new HashSet<String>();
for (Game game : retrievedGames) {
System.out.println("* " + game);
retrievedGameTitles.add(game.getTitle());
}
Assert.assertTrue(retrievedGameTitles.containsAll(Arrays.asList(GAME_TITLES)));
}
@Before
public void preparePersistenceTest() throws Exception {
clearData();
insertData();
startTransaction();
}
private void clearData() throws Exception {
utx.begin();
em.joinTransaction();
System.out.println("Dumping old records...");
em.createQuery("delete from Game").executeUpdate();
utx.commit();
}
private void insertData() throws Exception {
utx.begin();
em.joinTransaction();
System.out.println("Inserting records...");
for (String title : GAME_TITLES) {
Game game = new Game(title);
em.persist(game);
}
utx.commit();
// clear the persistence context (first-level cache)
em.clear();
}
private void startTransaction() throws Exception {
utx.begin();
em.joinTransaction();
}
@After
public void commitTransaction() throws Exception {
utx.commit();
}
}
'create = true' не обязательно, поскольку по умолчанию свойство true. 'create = false' используется, когда вы хотите, чтобы база данных уже была создана при попытке нового подключения. – fredt
@fredt Спасибо за обновление. В то время я делал ряд изменений, и у havent была возможность повторно посетить это. Я переучиваю позже и при необходимости отправлю EDIT – Romski