{“error”:”Entity type ‘AspNetUserRoles’ has composite primary key defined with data annotations. To set composite primary key, use fluent API.”}

When a database table has composite keys (multiple columns are in the key) you cannot use the usual key definition

[Key]
[Display(Name = “UserId”)]
public string UserId { get; set; }

[Key]
[Display(Name = “RoleId”)]
public string RoleId { get; set; }

When you run the application you get the error message:

{“error”:”Entity type ‘AspNetUserRoles’ has composite primary key defined with data annotations. To set composite primary key, use fluent API.”}

To declare composite keys, in the fluent API format

In the model declare the keys

public class AspNetUserRoles {

    // Composite primary keys
    // Initialized in ApplicationDbContext.OnModelCreating()
    public object UserId { get; internal set; }
    public object RoleId { get; internal set; }
    ...

In the ApplicationDbContext file add the lines to the OnModelCreating(ModelBuilder builder) method

// Composite primary key
builder.Entity().HasKey(table => new {
   table.UserId,
   table.RoleId
});

 

 

Generate SQL script from Entity Framework migration script

It is not recommended to execute Entity Framework migration scripts in production, It is important that you execute all SQL steps manually on the production database section-by-section to immediately see the result and be able to recover in case a destructive action goes wrong.

The Visual Studio .NET application templates contain Entity Framework migration scripts to set up your local database to match the sample code. To generate the SQL script you can execute by hand on the production database

Install the EF Core .NET Command-line Tools

  1. Open a command window in the folder of the project that contains the database access code
  2. In the command line execute
    dotnet add package Microsoft.EntityFrameworkCore.Design
    dotnet restore
  3. Test the dotnet ef installation with
    dotnet ef

 

Script the .NET Entity Framework migrations

  1. Open a command window in the folder of the project that contains the database access code
  2. In the command line execute
    1. To generate the SQL script to bring the current development database to the scripted configuration state, use the –idempotent option.
      (Generating idempotent scripts for migration is not currently supported by MySql)

      dotnet ef migrations script --idempotent --output "script.sql" --context MY_DBCONTEXT
    2. To generate the SQL script based on the entire migration script to update the production database to match the template after you have updated the development database
      dotnet ef migrations script --output "script.sql" --context MY_DBCONTEXT

 

 

DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded.

The .NET Core Entity framework makes database access easy. When you auto-generate a Razor page in a .NET web application to edit a data row, the scaffolding places controls on the page for every column.

There are columns in most of the tables that we don’t want to display or edit, like keys, checksums, password hashes. If column values are missing during database update, the error is thrown:

A database operation failed while processing the request.
DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.

When the edit page is displayed, all values of the row are passed to the page in the Model. When the user clicks the Save button the model is sent back to the server, and the OnPostAsync() method saves the values to the database. The values that we don’t display or store otherwise on the web page are not retained in the browser, and not passed back to the server. To keep the not displayed values, add hidden attributes to the page. The primary key of the row is automatically added, and based on that create hidden attributes for the rest of the not displayed columns.

 <form method="post">
 <div asp-validation-summary="ModelOnly" class="text-danger"></div>
 <input type="hidden" asp-for="ApplicationUser.Id" />
 <input type="hidden" asp-for="ApplicationUser.AccessFailedCount" />
 <input type="hidden" asp-for="ApplicationUser.ConcurrencyStamp" />
 <input type="hidden" asp-for="ApplicationUser.NormalizedEmail" />
 <input type="hidden" asp-for="ApplicationUser.NormalizedUserName" />
 <input type="hidden" asp-for="ApplicationUser.PasswordHash" />
 <input type="hidden" asp-for="ApplicationUser.SecurityStamp" />
 <input type="hidden" asp-for="ApplicationUser.UserName" />

 

 

 

java.lang.NoClassDefFoundError, java.lang.ClassNotFoundException

When you add a dependency reference to a Java project, it may compile without any errors, but runtime you may get an error message similar to this:

HTTP Status 500 – Internal Server Error

Type Exception Report

Message An exception occurred processing JSP page [/index.jsp] at line [1]

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.apache.jasper.JasperException: An exception occurred processing JSP page [/index.jsp] at line [1]

1: <jsp:forward page=”….html” />

Root Cause

javax.servlet.ServletException: Servlet.init() for servlet [spring] threw exception…

Root Cause

java.lang.NoClassDefFoundError: org/springframework/core/env/PropertySource…

Root Cause

java.lang.ClassNotFoundException: org.springframework.core.env.PropertySource…

If the newly added dependency also depends on another package, and that package is already in the pom.xml file, NetBeans will not show an error during build.

If the newly added dependency was recently introduced, and the version of the package already included in the pom.xml file,  references an earlier version, the runtime error will occur.

For example org.springframework.web.bind.annotation.GetMapping was introduced in Spring Web 4.0

If your pom.xml file already contains the reference to spring-web or spring-webmvc version 3, your application will fail runtime.

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>

In your web browser navigate to the Maven repository at https://mvnrepository.com/artifact/org.springframework and search for the spring-web and spring-webmvc packages. Get the latest stable version numbers and update your pom.xml file.

 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>5.0.2.RELEASE</version>
 </dependency>

 

 

Java Spring MVC web application configuration in NetBeans 8

When you create a Java Spring MVC web application or make changes to an existing one, it is important to know the location of configuration values.

Java package name

The Java package name is stored in

  • Every .java file
    • package MY_PACKAGE_NAME
  • pom.xml file
    • <configuration>
        <mainClass>com.objectdb.Enhancer</mainClass>
          <arguments>
            <argument>MY_PACKAGE_NAME.MY_MAIN_CLASS_NAME</argument>
          </arguments>
      </configuration>
  • .jsp file
    • <%@page import=”MY_PACKAGE_NAME.*”%>
    • <jsp:useBean id=”MY_BEAN_ID” type=”MY_PACKAGE_NAME.MY_DAO_CLASS_NAME” scope=”request” />

WAR file name

The name of the WAR fle is set in the

  • pom.xml file
    • <finalName>MY_WAR_FILE_NAME</finalName>

Add references to external classes

When you copy a class from another project, you need to add references to the imported external classes. When you build your project, the missing references will be in the output window.

————————————————————-
COMPILATION ERROR :
————————————————————-
webapp/twitter_keywordsRepository.java:[3,42] error: package org.springframework.data.repository does not exist

To add the reference to the project

  1. Click the error message link in the output window,
  2. Click the light bulb in the line of the error,
  3. In the context menu select Search Dependency at Maven Repositories for
  4. Select the recommended Maven repository, and click the Add button.

The references are stored in the

  • pom.xml file under
    • <dependencies>

 

 

 

org.apache.jasper.JasperException: java.lang.IllegalStateException: No output folder

This error can happen on Linux and Windows, and the cause could be the same.

On Windows Server 2012R2 I opened a command prompt. To be able to delete a directory from the Tomcat webapps folder, I have issued the shutdown command.

When I started the server with the startup command, and navigated to my local website, my Java Spring MVC web application displayed the error message

org.apache.jasper.JasperException: java.lang.IllegalStateException: No output folder

The problem was, that the Tomcat service runs under root on Linux, and SYSTEM on Windows.

When you issue the startup command, Tomcat will run under the user account you logged in with.

Solution:

Stop and start the TomCat Linux or Windows service instead of issuing the shutdown and startup commands from the terminal or command prompt.

 

Only persistence units with transaction type JTA can be used as a container managed entity manager

NetBeans can use multiple deployment servers. When your web application uses the Entity Framework and you select the Glassfish server as the deployment server, you can get the error message when you try to run your application in the IDEÉ

Severe: Exception while preparing the app : The persistence-context-ref-name […] in module […] resolves to a persistence unit called […] which is of type RESOURCE_LOCAL. Only persistence units with transaction type JTA can be used as a container managed entity manager. Please verify your application.

When you first run the application NetBeans asks you to select the deployment server you want to use.

If only the Glassfish server is available, and Tomcat is installed on your workstation, add Tomcat to the available deployment servers.

Install Tomcat

For the Tomcat installation see Tomcat web server installation

Add Tomcat to the NetBeans server list

  1. In the Tools menu select Servers
  2. Click the Add Server button
  3. In the list select the Apache Tomcat or TomEEE server
  4. Click the Browse… button
  5. Select the Tomcat directory on your workstation
  6. Enter a Tomcat username and password for NetBeans, and click the Finish button.
  7. The user will be created in the tomcat-users.xml file in the Tomcat conf directory
  8. Click the Close button.

Select the Deployment Server

  1. Right-click the NetBeans project and select Run
  2. In the Select deployment server window select Apache Tomcat or TomEE

If the Select deployment server window does not pop up

  1. Right-click the NetBeans project and select Set Configuration -> Customize
  2. On the Run tab select the Apache server.

Starting of Tomcat failed, the server port 8080 is already in use

  1. If the Glassfish server already started, Tomcat cannot use the same ports and an error message will appear in the NetBeans RunOutput tab
  2. To stop the Glassfish server, restart your workstation.

Install Git on Windows

If you use two-factor authentication see Create a Personal Access Token to use it as password in the command line tools at Switching to 2-factor authentication in GitHub

  1. Navigate to https://git-scm.com/download/win to download Git for Windows. The page automatically downloads the installer for the operating system you use.
  2. Install the application
  3. Accept the default values, including these:
    1. Make sure the Windows Explorer integration for Git Bash is checked.
    2. Enable the Git tools in the command prompt too
    3. HTTPS transport backend. For large corporations with internal root certificates and  Windows Active Directory, the second option may be a better choice,
    4. Line endings for Windows computers
    5. Terminal emulator
    6. Caching
    7. Finish the installation.

Configure Git for Windows

Enable Page Up and Page Down

  1. In Windows Explorer right click in the white area and select Git Bash Here,

  2. Stretch the Bash window to the full width of the page to have more room to work later,
  3. Right-click the Bash window and select Options…,
  4. On the Window tab,
    1. Click the Current size button to save the size,
    2. Select PgUp and PgDn scroll without modifier to be able to scroll quickly up and down in the window with the Page up and Page down buttons.

Set up Git Bash to always run as Administrator

Certain commands need elevated rights to run, so we will set up the Bash window to run as administrator.

  1. Click the Windows Start button and type bash
  2. Right-click the found link and select Open file location

  3. Right-click the menu shortcut and select Properties
  4. On the Compatibility tab select Run this program as administrator

Using the Bash window

  • When you will start the Git Bash window you will always get the confirmation popup.

You can start the Git Bash window from the Windows Explorer

  1. Right-click a white area in Windows Explorer and select Git Bash Here. This does not work in the shared folders of Windows 10 virtual machines.

Configure the Git command line tool

To configure Git see Git configuration.

Deploy a WAR file of a Java web application on the Apache Tomcat web server

There are two ways to deploy a WAR file of a Java web application on the Apache Tomcat web server

Using the command line

  1. Copy the WAR file into the webapps folder of the Tomcat installation directory,
  2. Make sure the CATALINA_HOME environment variable points to the Tomcat directory (not the bin subdirectry)
  3. Open a Terminal window or Command Prompt,
  4. Navigate to the bin directory of the Tomcat web server installation directory,
  5. Execute
    startup
  6. Tomcat will unzip the war file into a directory named after the WAR file and display the message similar to this.

    C:\Program Files\apache-tomcat-8.5.23\bin>startup
    Using CATALINA_BASE: “C:\Program Files\apache-tomcat-8.5.23”
    Using CATALINA_HOME: “C:\Program Files\apache-tomcat-8.5.23”
    Using CATALINA_TMPDIR: “C:\Program Files\apache-tomcat-8.5.23\temp”
    Using JRE_HOME: “C:\Program Files\Java\jre-9.0.1”
    Using CLASSPATH: “C:\Program Files\apache-tomcat-8.5.23\bin\bootstrap.jar;C:\Program Files\apache-tomcat-8.5.23\bin\tomcat-juli.jar”C:\Program Files\apache-tomcat-8.5.23\bin>

Using the Tomcat user interface

  1. Remote into the web server,
  2. Copy the WAR file to a temp directory,
  3. Open the Tomcat web user interface at http://localhost:8080/manager
  4. Log in with the credentials specified for the manager-gui role in the tomcat-users.xml file of the conf Tomcat folder,
  5. In WAR file to deploy section click the Choose File button and select the WAR file,
  6. Click the Deploy button,
  7. Tomcat will unzip the war file into a directory named after the WAR file in the webapps folder of the Tomcat installation directory.

Create a WAR file for a Java web application in NetBeans

Configure the web application

Add the web.xml file

The wb.xml file contains the web application configuration values for the webserver. I has to be in the WEB-INF directory of the web applicaion. To add the web.xml file to your NetBeans Java web application

  1. Right-click the Netbeans project, and select New -> Other
  2. In the New File window select XML -> XML Document, and click the Next button,
  3. In the New XML Document window enter web.xml as the name of the file, and click the Browse… button to select the location,
  4. Select the src\main\webapp\WEB-INF folder, and click the Select Folder button,
  5. In the New XML Document window click the Next button,
  6. In the New File window keep the Well-formed Document radio button selected and click the Finish button,
  7. NetBeans creates the XML file in the Web PAges WEB-INF folder on the web project.

Build the WAR file

To create a WAR file for a Java web application in NetBeans 8.2

  1. In the NetBeans IDE select the Files tab,
  2. Right-click the pom.xml file and select Run Maven > Goals…
  3. In the Run Maven window enter compile war:war into the Goals field,
  4. Select the Remember as checkbox and enter Compile war for the name,
  5. The WAR file is generated in the target directory of the Java web project.
  6. The next time you want to build the WAR file, the Compile war option will be visible in the Run Maven menu.