---
title: Java sample to backfill customers in Stripe and Amberflo from Postgres
slug: docs/create-customers-from-postgres
createdAt: 2024-07-11T14:53:07.014Z
---

The following Java sample demonstrates how to **create customers in both Stripe and Amberflo** using data from a **Postgres database.**
This example outlines a typical customer backfill workflow where you sync customer records across systems and link them using shared identifiers.

The sample performs the following steps:

1. Queries the **customer table** in your Postgres database.
2. For each row:
   - Checks if the customer already exists in **Amberflo**.
   - If not:
     - Creates the customer in **Stripe**.
     - Creates the customer in **Amberflo**, setting the Stripe customer ID as a trait.
     - Assigns the customer to a **default rate plan**.

This approach ensures a smooth backfill process, maintaining consistency between your billing platform (Stripe) and your usage-based metering system (Amberflo).

**Maven dependencies** (check for latest versions):

:::CodeblockTabs
pom.xml

```xml
<dependencies>
  <dependency>
    <groupId>io.amberflo</groupId>
    <artifactId>metering-java-client</artifactId>
    <version>1.3.6</version>
  </dependency>
  <dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.3.1</version>
  </dependency>
  <dependency>
    <groupId>com.stripe</groupId>
    <artifactId>stripe-java</artifactId>
    <version>20.52.0</version>
  </dependency>
</dependencies>
```
:::

Sample Java Code:

```java
import com.amberflo.metering.customer_details.clients.CustomerDetailsClient;
import com.amberflo.metering.customer_details.clients.CustomerProductPlanClient;
import com.amberflo.metering.customer_details.model.CustomerDetails;
import com.amberflo.metering.customer_details.model.CustomerProductPlan;
import com.stripe.Stripe;
import com.stripe.model.Customer;
import com.stripe.param.CustomerCreateParams;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

public class CustomerPostgresBackfillProvider {
  
  	//TODO: set the database connection, queries, Amberflo, and Stripe info 
    final static String DB_HOST = "sample-host.us-west-2.rds.amazonaws.com";
    final static String DB_NAME = "sampleDb";
    final static String DB_PASS = "sample-pass";
    final static String DB_USER = "sample-user";
    final static String SCHEMA = "sampleSchema";
  	final static String COUNT_QUERY = "SELECT count(*) AS total FROM customers;";
    final static String SELECT_QUERY = "SELECT id, customerName, customerAlternateId, email FROM customers;";
    final static String AMBERFLO_PRODUCT_PLAN_ID = "default-product-plan-id";
    final static String AMBERFLO_API_KEY = "amberflo-api-key";
    final static String STRIPE_API_KEY = "sk-api-key";
  	//END TODO
  
    final static CustomerProductPlanClient customerProductPlanClient = new CustomerProductPlanClient(AMBERFLO_API_KEY);
    final static CustomerDetailsClient customerDetailsClient = new CustomerDetailsClient(AMBERFLO_API_KEY);
    static int counter = 0;
    static int existing = 0;

    public static void main(final String[] args) throws Exception {
        Statement stmt = null;
        Connection con = null;
        ResultSet rs = null;
        try {
            final String url = String.format("jdbc:postgresql://%s:5432/%s?currentSchema=%s", DB_HOST, DB_NAME, SCHEMA);
            con = DriverManager.getConnection(url, DB_USER, DB_PASS);
            stmt = con.createStatement();
            //query to get count of customers
            rs = stmt.executeQuery(COUNT_QUERY);
            rs.next();
            int total = rs.getInt("total");
            System.out.println("Total customers = " + total);

          	//Read all customer rows from database table
            rs = stmt.executeQuery(SELECT_QUERY);
            while (rs.next()) {
                int id = rs.getInt("id");
                final String customerName = rs.getString("customerName");
                final String customerAlternateId = rs.getString("customerAlternateId");
                final String email = rs.getString("email");
                System.out.println(String.format("ID=%s, customerName=%s, customerAlternateId=%s, email=%s",
                        id, customerName, customerAlternateId, email));
                createCustomerInStripeAndAmberflo(Integer.toString(id), email, customerName, customerAlternateId);
            }
            System.out.println("DONE!!! Total customers migrated = " + counter);
            System.out.println("Customers that already existed = " + existing);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (con != null) con.close();
        }
    }

    private static void createCustomerInStripeAndAmberflo(final String customerId,
                                                          final String customerEmail,
                                                          final String customerName,
                                                          final String customerAlternateId
    ) {
        try {
            Stripe.apiKey = STRIPE_API_KEY;
            final Map<String, String> metadata = new HashMap();
            metadata.put("customerId", customerId);
            metadata.put("customerAlternateId", customerAlternateId);

            final CustomerCreateParams params = CustomerCreateParams
                    .builder()
                    .setEmail(customerEmail)
                    .setMetadata(metadata)
                    .build();


            //check if customer does not already exist in Amberflo
            final CustomerDetails customerDetails1 = customerDetailsClient.get(customerId);
            if (customerDetails1 != null
                    && customerId.equals(customerDetails1.getCustomerId())
                    && customerDetails1.getTraits().containsKey("stripeId")) {
                System.out.println(String.format("Amberflo: Customer with id %s already exists in Amberflo and in Stripe with id %s, so skipping ...",
                        customerId, customerDetails1.getTraits().get("stripeId")));
                existing++;
                return;
            }

            //create customer in Stripe
            final Customer stripeCustomer = Customer.create(params);
            System.out.println(String.format("Amberflo: Customer with id %s created in Stripe with id %s",
                    customerId, stripeCustomer.getId()));

            final Map<String, String> traits = new HashMap();
            traits.put("customerAlternateId", customerAlternateId);
            traits.put("stripeId", stripeCustomer.getId());
            final CustomerDetails customerDetails = new CustomerDetails(customerId, customerName, customerEmail, traits);

            //create customer in Amberflo
            customerDetailsClient.addOrUpdate(customerDetails);
            System.out.println(String.format("Amberflo: Customer with id %s created in Amberflo",
                    customerId));

            //Assign customer to a default product plan
            final String productPlanId = AMBERFLO_PRODUCT_PLAN_ID;
            final CustomerProductPlan customerProductPlan = new CustomerProductPlan(productPlanId, customerId);
            customerProductPlanClient.addOrUpdate(customerProductPlan);
            System.out.println(String.format("Amberflo: Customer with id %s assigned to product plan %s in Amberflo",
                    customerId, productPlanId));
            counter++;
        } catch (Exception ex) {
            System.out.println(String.format("Amberflo customer creation failed: %s", ex.getMessage()));
            ex.printStackTrace();
        }
    }
}
```

